diff options
| author | Botahamec <botahamec@outlook.com> | 2024-03-07 00:18:27 -0500 |
|---|---|---|
| committer | Botahamec <botahamec@outlook.com> | 2024-03-07 00:18:27 -0500 |
| commit | 83fdb1048f6e5c10200110d1810a48e7a34c6cf4 (patch) | |
| tree | 93c3cdf9d6b2d6effe92cad57e81b4766b8097d3 /examples/list.rs | |
| parent | e706252f3cc716e07be58c202c13394873922be2 (diff) | |
Example with list
Diffstat (limited to 'examples/list.rs')
| -rw-r--r-- | examples/list.rs | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/examples/list.rs b/examples/list.rs new file mode 100644 index 0000000..904d9f2 --- /dev/null +++ b/examples/list.rs @@ -0,0 +1,53 @@ +use std::thread; + +use happylock::mutex::Mutex; +use happylock::{LockGuard, ThreadKey}; + +const N: usize = 10; + +static DATA: [Mutex<usize>; 6] = [ + Mutex::new(0), + Mutex::new(1), + Mutex::new(2), + Mutex::new(3), + Mutex::new(4), + Mutex::new(5), +]; + +static SEED: Mutex<u32> = Mutex::new(42); + +fn random(key: ThreadKey) -> (ThreadKey, usize) { + let mut seed = SEED.lock(key); + let x = *seed; + let x = x ^ (x << 13); + let x = x ^ (x >> 17); + let x = x ^ (x << 5); + *seed = x; + (Mutex::unlock(seed), x as usize) +} + +fn main() { + for _ in 0..N { + thread::spawn(move || { + let mut key = ThreadKey::lock().unwrap(); + let mut rand; + let mut data = Vec::new(); + for _ in 0..3 { + (key, rand) = random(key); + data.push(&DATA[rand % 6]); + } + + let data = [data[0], data[1], data[2]]; + let mut guard = LockGuard::lock(&data, key); + *guard[0] += *guard[1]; + *guard[1] += *guard[2]; + *guard[2] += *guard[0]; + }); + } + + let key = ThreadKey::lock().unwrap(); + let data = LockGuard::lock(&DATA, key); + for val in &*data { + println!("{}", **val); + } +} |
