summaryrefslogtreecommitdiffstats
path: root/third_party/rust/crossbeam-epoch-0.8.2/examples/sanitize.rs
blob: 12f1263122a2f9b3dd8a43e4a6f839650e0a14f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
extern crate crossbeam_epoch as epoch;
extern crate rand;

use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};

use epoch::{Atomic, Collector, LocalHandle, Owned, Shared};
use rand::Rng;

fn worker(a: Arc<Atomic<AtomicUsize>>, handle: LocalHandle) -> usize {
    let mut rng = rand::thread_rng();
    let mut sum = 0;

    if rng.gen() {
        thread::sleep(Duration::from_millis(1));
    }
    let timeout = Duration::from_millis(rng.gen_range(0, 10));
    let now = Instant::now();

    while now.elapsed() < timeout {
        for _ in 0..100 {
            let guard = &handle.pin();
            guard.flush();

            let val = if rng.gen() {
                let p = a.swap(Owned::new(AtomicUsize::new(sum)), AcqRel, guard);
                unsafe {
                    guard.defer_destroy(p);
                    guard.flush();
                    p.deref().load(Relaxed)
                }
            } else {
                let p = a.load(Acquire, guard);
                unsafe { p.deref().fetch_add(sum, Relaxed) }
            };

            sum = sum.wrapping_add(val);
        }
    }

    sum
}

fn main() {
    for _ in 0..100 {
        let collector = Collector::new();
        let a = Arc::new(Atomic::new(AtomicUsize::new(777)));

        let threads = (0..16)
            .map(|_| {
                let a = a.clone();
                let c = collector.clone();
                thread::spawn(move || worker(a, c.register()))
            })
            .collect::<Vec<_>>();

        for t in threads {
            t.join().unwrap();
        }

        unsafe {
            a.swap(Shared::null(), AcqRel, epoch::unprotected())
                .into_owned();
        }
    }
}