Global threadId caching

This commit is contained in:
mdecimus
2024-03-04 18:51:24 +01:00
parent 31bc716a5f
commit ff279b3a39
16 changed files with 208 additions and 184 deletions

View File

@@ -21,7 +21,11 @@
* for more details.
*/
use std::{collections::HashMap, sync::Arc};
use std::{
collections::HashMap,
sync::{atomic::AtomicU64, Arc},
time::SystemTime,
};
use config::Config;
@@ -110,6 +114,41 @@ impl AsMut<[u8]> for BlobHash {
self.0.as_mut()
}
}
#[derive(Clone)]
pub struct CachedItem<T> {
last_access: Arc<AtomicU64>,
item: Arc<tokio::sync::Mutex<T>>,
}
impl<T> CachedItem<T> {
pub fn new(item: T) -> Self {
Self {
last_access: Arc::new(AtomicU64::new(
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map_or(0, |d| d.as_secs()),
)),
item: Arc::new(tokio::sync::Mutex::new(item)),
}
}
pub async fn get(&self) -> tokio::sync::MutexGuard<'_, T> {
let lock = self.item.lock().await;
self.last_access.store(
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map_or(0, |d| d.as_secs()),
std::sync::atomic::Ordering::Relaxed,
);
lock
}
pub fn last_access(&self) -> u64 {
self.last_access.load(std::sync::atomic::Ordering::Relaxed)
}
}
pub trait UnwrapFailure<T> {
fn failed(self, action: &str) -> T;
}