boolean_flag/
boolean_flag.rs1use prism3_atomic::AtomicBool;
14use std::sync::Arc;
15use std::thread;
16use std::time::Duration;
17
18fn main() {
19 println!("=== Atomic Boolean Flag Example ===\n");
20
21 println!("1. Simple Flag:");
23 let flag = AtomicBool::new(false);
24 println!(" Initial value: {}", flag.load());
25
26 flag.store(true);
27 println!(" After set(true): {}", flag.load());
28
29 flag.fetch_not();
30 println!(" After negate: {}", flag.load());
31
32 println!("\n2. One-time Initialization:");
34 let initialized = Arc::new(AtomicBool::new(false));
35 let mut handles = vec![];
36
37 for i in 0..5 {
38 let initialized = initialized.clone();
39 let handle = thread::spawn(move || {
40 if initialized.set_if_false(true).is_ok() {
41 println!(" Thread {} performed initialization", i);
42 thread::sleep(Duration::from_millis(100));
43 } else {
44 println!(" Thread {} skipped (already initialized)", i);
45 }
46 });
47 handles.push(handle);
48 }
49
50 for handle in handles {
51 handle.join().unwrap();
52 }
53
54 println!(" Final state: initialized = {}", initialized.load());
55
56 println!("\n3. Producer-Consumer Signaling:");
58 let ready = Arc::new(AtomicBool::new(false));
59 let data = Arc::new(AtomicBool::new(false));
60
61 let ready_clone = ready.clone();
62 let data_clone = data.clone();
63
64 let producer = thread::spawn(move || {
66 println!(" Producer: preparing data...");
67 thread::sleep(Duration::from_millis(100));
68 data_clone.store(true);
69 ready_clone.store(true);
70 println!(" Producer: data ready!");
71 });
72
73 let consumer = thread::spawn(move || {
75 println!(" Consumer: waiting for data...");
76 while !ready.load() {
77 thread::yield_now();
78 }
79 println!(" Consumer: received data = {}", data.load());
80 });
81
82 producer.join().unwrap();
83 consumer.join().unwrap();
84
85 println!("\n4. Toggle Operations:");
87 let flag = Arc::new(AtomicBool::new(false));
88 let mut handles = vec![];
89
90 for i in 0..10 {
91 let flag = flag.clone();
92 let handle = thread::spawn(move || {
93 for _ in 0..10 {
94 flag.fetch_not();
95 }
96 println!(" Thread {} completed 10 toggles", i);
97 });
98 handles.push(handle);
99 }
100
101 for handle in handles {
102 handle.join().unwrap();
103 }
104
105 println!(" Final state: {} (after 100 toggles)", flag.load());
106
107 println!("\n=== Example completed ===");
108}