ref_once/
ref_once.rs

1use std::{mem::MaybeUninit, thread};
2
3use scope_lock::RefOnce;
4
5fn main() {
6    let mut a = vec![1, 2, 3];
7    let mut x = 0;
8
9    let mut slots = (MaybeUninit::uninit(), MaybeUninit::uninit());
10
11    scope_lock::lock_scope(|e| {
12        thread::spawn({
13            let f = e.fn_(RefOnce::new(
14                |()| {
15                    println!("hello from the first scoped thread");
16                    // We can borrow `a` here.
17                    dbg!(&a);
18                },
19                &mut slots.0,
20            ));
21            move || f(())
22        });
23        thread::spawn({
24            let mut f = e.fn_mut(RefOnce::new(
25                |()| {
26                    println!("hello from the second scoped thread");
27                    // We can even mutably borrow `x` here,
28                    // because no other threads are using it.
29                    x += a[0] + a[2];
30                },
31                &mut slots.1,
32            ));
33            move || f(())
34        });
35        println!("hello from the main thread");
36    });
37
38    // After the scope, we can modify and access our variables again:
39    a.push(4);
40    assert_eq!(x, a.len());
41}