Skip to content

Instantly share code, notes, and snippets.

@jberkenbilt
Last active December 1, 2024 19:13
Show Gist options
  • Save jberkenbilt/423a8410e9c1b5e5ffa73cee730656dd to your computer and use it in GitHub Desktop.
Save jberkenbilt/423a8410e9c1b5e5ffa73cee730656dd to your computer and use it in GitHub Desktop.
Go to Rust: 04 tokio runtime
use crate::rwlock::TokioLockWrapper;
use base::{AsyncRwLock, Locker, Runtime};
pub mod rwlock;
#[derive(Default, Clone)]
pub struct TokioRuntime;
impl Locker for TokioRuntime {
fn new_lock<T: Sync + Send>(item: T) -> impl AsyncRwLock<T> {
TokioLockWrapper::<T>::new(item)
}
}
impl Runtime for TokioRuntime {}
use base::AsyncRwLock;
use std::ops::{Deref, DerefMut};
use tokio::sync;
#[derive(Default)]
pub struct TokioLockWrapper<T> {
lock: sync::RwLock<T>,
}
impl<T: Sync + Send> AsyncRwLock<T> for TokioLockWrapper<T> {
fn new(item: T) -> Self {
TokioLockWrapper {
lock: sync::RwLock::new(item),
}
}
async fn read(&self) -> impl Deref<Target = T> + Sync + Send {
self.lock.read().await
}
async fn write(&self) -> impl DerefMut<Target = T> + Sync + Send {
self.lock.write().await
}
}
#[cfg(test)]
mod tests;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment