real_world_test/
real_world_test.rs

1use ida_rs::Ida;
2use std::sync::Arc;
3use std::thread;
4
5fn main() {
6    println!("Simulating a real-world scenario with multiple threads...");
7
8    let allocator = Arc::new(Ida::new());
9    let mut handles = vec![];
10
11    // Spawn 5 threads. Each will try to allocate 3 IDs.
12    for i in 0..5 {
13        let allocator_clone = Arc::clone(&allocator);
14        let handle = thread::spawn(move || {
15            let mut allocated_ids = vec![];
16            for _ in 0..3 {
17                match allocator_clone.alloc() {
18                    Some(id) => {
19                        println!("Thread {i} allocated ID: {id}");
20                        allocated_ids.push(id);
21                    }
22                    None => {
23                        println!("Thread {i} failed to allocate an ID.");
24                    }
25                }
26                // Simulate some work
27                thread::sleep(std::time::Duration::from_millis(10));
28            }
29            allocated_ids
30        });
31        handles.push(handle);
32    }
33
34    // Wait for all threads to finish and collect the results
35    let mut all_ids = vec![];
36    for handle in handles {
37        all_ids.extend(handle.join().unwrap());
38    }
39
40    println!("\nAll threads finished.");
41    println!("Total IDs allocated: {}", all_ids.len());
42    println!("Allocated IDs: {all_ids:?}");
43
44    // Verify correctness: sort and check for duplicates
45    all_ids.sort();
46    let mut unique_ids = all_ids.clone();
47    unique_ids.dedup();
48
49    assert_eq!(
50        all_ids.len(),
51        unique_ids.len(),
52        "Error: Duplicate IDs were allocated!"
53    );
54
55    println!("\nVerification successful: No duplicate IDs were issued.");
56}