summaryrefslogtreecommitdiff
path: root/examples/list.rs
diff options
context:
space:
mode:
authorMica White <botahamec@outlook.com>2024-03-08 11:45:15 -0500
committerMica White <botahamec@outlook.com>2024-03-08 11:45:15 -0500
commit6b4951ade670acbe3cb34b2002fbcd4b4e6a7300 (patch)
treec800e9888ba649e2cff27cc1b8ae001c3632572d /examples/list.rs
parentcff337867884fc5d9eff80c77d41e64ee53c6115 (diff)
Replace ownership with mutable access
Diffstat (limited to 'examples/list.rs')
-rw-r--r--examples/list.rs19
1 files changed, 9 insertions, 10 deletions
diff --git a/examples/list.rs b/examples/list.rs
index 904d9f2..c73b54e 100644
--- a/examples/list.rs
+++ b/examples/list.rs
@@ -1,11 +1,11 @@
use std::thread;
-use happylock::mutex::Mutex;
+use happylock::mutex::{Mutex, SpinLock};
use happylock::{LockGuard, ThreadKey};
const N: usize = 10;
-static DATA: [Mutex<usize>; 6] = [
+static DATA: [SpinLock<usize>; 6] = [
Mutex::new(0),
Mutex::new(1),
Mutex::new(2),
@@ -14,39 +14,38 @@ static DATA: [Mutex<usize>; 6] = [
Mutex::new(5),
];
-static SEED: Mutex<u32> = Mutex::new(42);
+static SEED: SpinLock<u32> = Mutex::new(42);
-fn random(key: ThreadKey) -> (ThreadKey, usize) {
+fn random(key: &mut 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)
+ 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);
+ let rand = random(&mut key);
data.push(&DATA[rand % 6]);
}
let data = [data[0], data[1], data[2]];
- let mut guard = LockGuard::lock(&data, key);
+ let mut guard = LockGuard::lock(&data, &mut key);
*guard[0] += *guard[1];
*guard[1] += *guard[2];
*guard[2] += *guard[0];
});
}
- let key = ThreadKey::lock().unwrap();
- let data = LockGuard::lock(&DATA, key);
+ let mut key = ThreadKey::lock().unwrap();
+ let data = LockGuard::lock(&DATA, &mut key);
for val in &*data {
println!("{}", **val);
}