use task_local::task_local;
task_local! {
static NUMBER: u32;
static MESSAGE: String;
}
async fn nested_function() {
println!("In nested_function: NUMBER = {}", NUMBER.get());
println!("In nested_function: MESSAGE = {}", MESSAGE.get());
println!("In nested_function: MESSAGE = {:?}", MESSAGE.try_get());
}
async fn example() {
NUMBER
.scope(42, async {
MESSAGE
.scope("Hello, task-local!".to_string(), async {
println!("NUMBER = {}", NUMBER.get());
println!("MESSAGE = {}", MESSAGE.get());
nested_function().await;
NUMBER
.scope(100, async {
println!("Inside nested scope: NUMBER = {}", NUMBER.get());
println!("Inside nested scope: MESSAGE = {}", MESSAGE.get());
})
.await;
println!("After nested scope: NUMBER = {}", NUMBER.get());
})
.await;
})
.await;
println!("NUMBER = {:?}", NUMBER.try_get());
}
fn sync_example() {
NUMBER.sync_scope(99, || {
println!("In sync_scope: NUMBER = {}", NUMBER.get());
NUMBER.sync_scope(999, || {
println!("In nested sync_scope: NUMBER = {}", NUMBER.get());
});
println!("After nested sync_scope: NUMBER = {}", NUMBER.get());
});
}
#[tokio::main]
async fn main() {
println!("Running async example:");
example().await;
println!("\nRunning sync example:");
sync_example();
}