use std::sync::Arc;
use tokio_rcu::{rcu_block_on, rcu_box::RcuBox};
#[derive(Debug, Clone)]
struct SharedState {
users: Vec<String>,
}
impl SharedState {
fn contains_user(&self, username: &str) -> bool {
self.users.iter().find(|x| *x == username).is_some()
}
}
fn main() {
rcu_block_on(async move {
let state = Arc::new(RcuBox::new(Box::new(SharedState { users: Vec::new() })));
let readers: Vec<_> = (0..16)
.map(|_| {
tokio::spawn({
let state = state.clone();
async move {
loop {
let contains_desired_user =
state.with(|state| state.contains_user("Alice"));
if contains_desired_user {
break;
}
tokio::task::yield_now().await;
}
}
})
})
.collect();
let mut cur_state = state.read_clone();
cur_state.users.push("Bob".into());
let mut old_state = state.swap(Box::new(cur_state)).await;
old_state.users.push("Alice".into());
state.swap(old_state).await;
for task in readers {
task.await.unwrap();
}
});
}