qubit-atomic 0.9.0

User-friendly atomic operations wrapper providing JDK-like atomic API
Documentation
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/*******************************************************************************
 *
 *    Copyright (c) 2025 - 2026.
 *    Haixing Hu, Qubit Co. Ltd.
 *
 *    All rights reserved.
 *
 ******************************************************************************/

use qubit_atomic::atomic::{
    AtomicBool,
    AtomicF32,
    AtomicI32,
    AtomicI64,
    AtomicRef,
    AtomicU32,
    AtomicUsize,
};
use std::sync::atomic::{
    AtomicUsize as StdAtomicUsize,
    Ordering,
};
use std::sync::{
    Arc,
    Barrier,
};
use std::thread;
use std::time::Duration;

const NUM_THREADS: usize = 10;
const ITERATIONS_PER_THREAD: usize = 1000;

// Test concurrent increments
#[test]
fn test_concurrent_increment() {
    let counter = Arc::new(AtomicI32::new(0));
    let mut handles = vec![];

    for _ in 0..NUM_THREADS {
        let counter = counter.clone();
        let handle = thread::spawn(move || {
            for _ in 0..ITERATIONS_PER_THREAD {
                counter.fetch_inc();
            }
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    assert_eq!(counter.load(), (NUM_THREADS * ITERATIONS_PER_THREAD) as i32);
}

// Test concurrent decrements
#[test]
fn test_concurrent_decrement() {
    let counter = Arc::new(AtomicI64::new(10000));
    let mut handles = vec![];

    for _ in 0..NUM_THREADS {
        let counter = counter.clone();
        let handle = thread::spawn(move || {
            for _ in 0..100 {
                counter.fetch_dec();
            }
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    assert_eq!(counter.load(), 10000 - (NUM_THREADS * 100) as i64);
}

// Test concurrent CAS operations
#[test]
fn test_concurrent_cas() {
    let atomic = Arc::new(AtomicU32::new(0));
    let success_count = Arc::new(StdAtomicUsize::new(0));
    let mut handles = vec![];

    for _ in 0..NUM_THREADS {
        let atomic = atomic.clone();
        let success_count = success_count.clone();
        let handle = thread::spawn(move || {
            let mut current = atomic.load();
            loop {
                match atomic.compare_set_weak(current, current + 1) {
                    Ok(_) => {
                        success_count.fetch_add(1, Ordering::Relaxed);
                        break;
                    }
                    Err(actual) => current = actual,
                }
            }
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    assert_eq!(atomic.load(), NUM_THREADS as u32);
    assert_eq!(success_count.load(Ordering::Relaxed), NUM_THREADS);
}

// Test concurrent swap operations
#[test]
fn test_concurrent_swap() {
    let atomic = Arc::new(AtomicI32::new(0));
    let mut handles = vec![];
    let sum = Arc::new(StdAtomicUsize::new(0));

    for i in 0..NUM_THREADS {
        let atomic = atomic.clone();
        let sum = sum.clone();
        let handle = thread::spawn(move || {
            let old = atomic.swap((i + 1) as i32);
            sum.fetch_add(old as usize, Ordering::Relaxed);
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    // The final value should be one of the thread IDs
    let final_value = atomic.load();
    assert!(final_value >= 1 && final_value <= NUM_THREADS as i32);
}

// Test concurrent boolean flag operations
#[test]
fn test_concurrent_flag() {
    let flag = Arc::new(AtomicBool::new(false));
    let success_count = Arc::new(StdAtomicUsize::new(0));
    let mut handles = vec![];

    for _ in 0..NUM_THREADS {
        let flag = flag.clone();
        let success_count = success_count.clone();
        let handle = thread::spawn(move || {
            if flag.set_if_false(true).is_ok() {
                success_count.fetch_add(1, Ordering::Relaxed);
            }
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    // Only one thread should succeed
    assert!(flag.load());
    assert_eq!(success_count.load(Ordering::Relaxed), 1);
}

// Test concurrent toggle operations
#[test]
fn test_concurrent_toggle() {
    let flag = Arc::new(AtomicBool::new(false));
    let mut handles = vec![];

    for _ in 0..NUM_THREADS {
        let flag = flag.clone();
        let handle = thread::spawn(move || {
            for _ in 0..100 {
                flag.fetch_not();
            }
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    // After even number of toggles, should be false
    assert!(!flag.load());
}

// Test concurrent floating-point additions
#[test]
fn test_concurrent_float_add() {
    let sum = Arc::new(AtomicF32::new(0.0));
    let mut handles = vec![];

    for _ in 0..NUM_THREADS {
        let sum = sum.clone();
        let handle = thread::spawn(move || {
            for _ in 0..100 {
                sum.fetch_add(0.01);
            }
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    // Due to floating point precision, result may not be exact
    let result = sum.load();
    let expected = (NUM_THREADS * 100) as f32 * 0.01;
    assert!((result - expected).abs() < 0.1);
}

// Test concurrent reference updates
#[test]
fn test_concurrent_ref_update() {
    let atomic = Arc::new(AtomicRef::new(Arc::new(0)));
    let mut handles = vec![];

    for _ in 0..NUM_THREADS {
        let atomic = atomic.clone();
        let handle = thread::spawn(move || {
            for _ in 0..100 {
                atomic.fetch_update(|current| {
                    let value = **current;
                    Arc::new(value + 1)
                });
            }
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    assert_eq!(*atomic.load(), NUM_THREADS * 100);
}

// Test concurrent accumulate operations
#[test]
fn test_concurrent_accumulate() {
    let atomic = Arc::new(AtomicI32::new(1));
    let mut handles = vec![];

    for _ in 0..5 {
        let atomic = atomic.clone();
        let handle = thread::spawn(move || {
            atomic.fetch_accumulate(2, |a, b| a * b);
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    // 1 * 2^5 = 32
    assert_eq!(atomic.load(), 32);
}

// Test concurrent max operations
#[test]
fn test_concurrent_max() {
    let atomic = Arc::new(AtomicI32::new(0));
    let mut handles = vec![];

    for i in 0..NUM_THREADS {
        let atomic = atomic.clone();
        let handle = thread::spawn(move || {
            atomic.fetch_max((i * 10) as i32);
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    assert_eq!(atomic.load(), ((NUM_THREADS - 1) * 10) as i32);
}

// Test concurrent min operations
#[test]
fn test_concurrent_min() {
    let atomic = Arc::new(AtomicI32::new(1000));
    let mut handles = vec![];

    for i in 0..NUM_THREADS {
        let atomic = atomic.clone();
        let handle = thread::spawn(move || {
            atomic.fetch_min((100 - i * 5) as i32);
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    assert_eq!(atomic.load(), (100 - (NUM_THREADS - 1) * 5) as i32);
}

// Test barrier synchronization with atomic operations
#[test]
fn test_barrier_sync() {
    let counter = Arc::new(AtomicUsize::new(0));
    let barrier = Arc::new(Barrier::new(NUM_THREADS));
    let mut handles = vec![];

    for _ in 0..NUM_THREADS {
        let counter = counter.clone();
        let barrier = barrier.clone();
        let handle = thread::spawn(move || {
            // All threads wait at the barrier
            barrier.wait();
            // Then all increment simultaneously
            counter.fetch_inc();
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    assert_eq!(counter.load(), NUM_THREADS);
}

// Test producer-consumer pattern with atomic flag
#[test]
fn test_producer_consumer() {
    let data = Arc::new(AtomicI32::new(0));
    let ready = Arc::new(AtomicBool::new(false));

    let data_clone = data.clone();
    let ready_clone = ready.clone();

    // Producer thread
    let producer = thread::spawn(move || {
        thread::sleep(Duration::from_millis(10));
        data_clone.store(42);
        ready_clone.store(true);
    });

    // Consumer thread
    let consumer = thread::spawn(move || {
        while !ready.load() {
            thread::yield_now();
        }
        data.load()
    });

    producer.join().unwrap();
    let result = consumer.join().unwrap();
    assert_eq!(result, 42);
}

// Test spinlock-like pattern
#[test]
fn test_spinlock_pattern() {
    let lock = Arc::new(AtomicBool::new(false));
    let counter = Arc::new(AtomicI32::new(0));
    let mut handles = vec![];

    for _ in 0..NUM_THREADS {
        let lock = lock.clone();
        let counter = counter.clone();
        let handle = thread::spawn(move || {
            for _ in 0..10 {
                // Acquire lock
                while lock.set_if_false(true).is_err() {
                    thread::yield_now();
                }

                // Critical section
                let value = counter.load();
                thread::yield_now(); // Simulate some work
                counter.store(value + 1);

                // Release lock
                lock.store(false);
            }
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    assert_eq!(counter.load(), (NUM_THREADS * 10) as i32);
}

// Test concurrent bitwise operations
#[test]
fn test_concurrent_bitwise() {
    let atomic = Arc::new(AtomicU32::new(0));
    let mut handles = vec![];

    for i in 0..NUM_THREADS {
        let atomic = atomic.clone();
        let handle = thread::spawn(move || {
            let bit = 1u32 << (i % 32);
            atomic.fetch_or(bit);
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    let result = atomic.load();
    // Check that all bits were set
    for i in 0..NUM_THREADS.min(32) {
        let bit = 1u32 << i;
        assert_eq!(result & bit, bit);
    }
}

// Test memory ordering visibility
#[test]
fn test_memory_ordering_visibility() {
    let data = Arc::new(AtomicI32::new(0));
    let flag = Arc::new(AtomicBool::new(false));

    let data_clone = data.clone();
    let flag_clone = flag.clone();

    let writer = thread::spawn(move || {
        data_clone.store(42);
        flag_clone.store(true);
    });

    let reader = thread::spawn(move || {
        while !flag.load() {
            thread::yield_now();
        }
        data.load()
    });

    writer.join().unwrap();
    let result = reader.join().unwrap();
    assert_eq!(result, 42);
}