my_flag/lib.rs
1//! Simple flag implementation for tokio.
2
3use std::sync::Arc;
4use tokio::sync::RwLock;
5
6/// Structure that consists of a `bool` wrapped in `Arc` and `RwLock` to ensure thread safety and protect against race conditions.
7/// Since the `RwLock` used is from the `tokio`, it can be used asynchronously.
8/// **Important:** Before passing the flag to a new thread clone it.
9#[derive(Clone)]
10pub struct Flag(pub Arc<RwLock<bool>>);
11
12impl Flag {
13 /// Creates a new `Flag`.
14 pub fn new(value: bool) -> Self {
15 Self(Arc::new(RwLock::new(value)))
16 }
17
18 /// Reads the boolean value of the `Flag` (without blocking other threads from reading the value as well).
19 pub async fn read(&self) -> bool {
20 *self.0.read().await
21 }
22
23 /// Write a new boolean value to the `Flag` (blocks read and write operations from all threads until completed).
24 pub async fn write(&self, value: bool) {
25 *self.0.write().await = value;
26 }
27
28 /// Creates a new reference to the flag so it can be used by a new thread.
29 pub fn clone(&self) -> Self {
30 Self(Arc::clone(&self.0))
31 }
32}