-
There is no problem with the first code, but it is ugly. The second code will report an error. Is there a way not to write ugly code? use std::{sync::RwLock, time::Duration};
#[tokio::main]
async fn main() {
let timeout = RwLock::new(Duration::from_secs(1));
tokio::spawn(async move {
tokio::time::sleep({
let timeout = timeout.read().unwrap().clone();
timeout
})
.await;
});
} use std::{sync::RwLock, time::Duration};
#[tokio::main]
async fn main() {
let timeout = RwLock::new(Duration::from_secs(1));
tokio::spawn(async move {
tokio::time::sleep({
timeout.read().unwrap().clone()
})
.await;
});
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
This topic is covered in the shared state chapter of the Tokio tutorial. The first question you should ask yourself is if you really need a lock at all. For example, could this work? use std::time::Duration;
#[tokio::main]
async fn main() {
let timeout = Duration::from_secs(1);
tokio::spawn(async move {
tokio::time::sleep(timeout).await;
});
} If you do need a lock for the purpose of having a shared value you can modify from several places, a good way to get cleaner code is to define the following helper struct: use std::time::Duration;
use std::sync::{Arc, RwLock};
#[derive(Clone)]
pub struct SharedDuration {
inner: Arc<RwLock<Duration>>,
}
impl SharedDuration {
pub fn new(value: Duration) -> Self {
Self {
inner: Arc::new(RwLock::new(value)),
}
}
pub fn set(&self, value: Duration) {
let mut lock = self.inner.write().unwrap();
*lock = value;
}
pub fn get(&self) -> Duration {
let lock = self.inner.read().unwrap();
*lock
}
}
#[tokio::main]
async fn main() {
let timeout = SharedDuration::new(Duration::from_secs(1));
tokio::spawn(async move {
tokio::time::sleep(timeout.get()).await;
});
} This value can be cloned to get a new handle to the same shared duration. If you call This technique is described under the Restructure your code to not hold the lock across an |
Beta Was this translation helpful? Give feedback.
-
Thank you for answering such a simple question in detail. I got the answer. |
Beta Was this translation helpful? Give feedback.
This topic is covered in the shared state chapter of the Tokio tutorial. The first question you should ask yourself is if you really need a lock at all. For example, could this work?
If you do need a lock for the purpose of having a shared value you can modify from several places, a good way to get cleaner code is to define the following helper struct: