summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rw-r--r--examples/basic.rs22
-rw-r--r--examples/double_mutex.rs27
2 files changed, 49 insertions, 0 deletions
diff --git a/examples/basic.rs b/examples/basic.rs
new file mode 100644
index 0000000..535b80a
--- /dev/null
+++ b/examples/basic.rs
@@ -0,0 +1,22 @@
+use std::thread;
+
+use happylock::mutex::Mutex;
+use happylock::ThreadKey;
+
+const N: usize = 10;
+
+static DATA: Mutex<i32> = Mutex::new(0);
+
+fn main() {
+ for _ in 0..N {
+ thread::spawn(move || {
+ let key = ThreadKey::lock().unwrap();
+ let mut data = DATA.lock(key);
+ *data += 1;
+ });
+ }
+
+ let key = ThreadKey::lock().unwrap();
+ let data = DATA.lock(key);
+ println!("{}", *data);
+}
diff --git a/examples/double_mutex.rs b/examples/double_mutex.rs
new file mode 100644
index 0000000..76f3294
--- /dev/null
+++ b/examples/double_mutex.rs
@@ -0,0 +1,27 @@
+use std::thread;
+
+use happylock::mutex::Mutex;
+use happylock::{LockGuard, ThreadKey};
+
+const N: usize = 10;
+
+static DATA_1: Mutex<i32> = Mutex::new(0);
+static DATA_2: Mutex<String> = Mutex::new(String::new());
+
+fn main() {
+ for _ in 0..N {
+ thread::spawn(move || {
+ let key = ThreadKey::lock().unwrap();
+ let data = (&DATA_1, &DATA_2);
+ let mut guard = LockGuard::lock(&data, key);
+ *guard.1 = (100 - *guard.0).to_string();
+ *guard.0 += 1;
+ });
+ }
+
+ let key = ThreadKey::lock().unwrap();
+ let data = (&DATA_1, &DATA_2);
+ let data = LockGuard::lock(&data, key);
+ println!("{}", *data.0);
+ println!("{}", *data.1);
+}