authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-06-12 17:16:34-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-06-12 17:43:49-07:00
log506b3f6db6c13bcced94c80ddf9bd871fb721cc0
treee5ab29569b0ead925fa4451d034c19d4ef4c0d49
parent55a9ea250cf2aad58f3c4eb49ac6ee8d2b6f5cff

introduce std.Thread.Mutex.Recursive


2 files changed, 110 insertions(+), 18 deletions(-)

lib/std/Thread/Mutex.zig+24-18
......@@ -1,23 +1,11 @@
1//! Mutex is a synchronization primitive which enforces atomic access to a shared region of code known as the "critical section".
2//! It does this by blocking ensuring only one thread is in the critical section at any given point in time by blocking the others.
3//! Mutex can be statically initialized and is at most `@sizeOf(u64)` large.
4//! Use `lock()` or `tryLock()` to enter the critical section and `unlock()` to leave it.
1//! Mutex is a synchronization primitive which enforces atomic access to a
2//! shared region of code known as the "critical section".
53//!
6//! Example:
7//! ```
8//! var m = Mutex{};
4//! It does this by blocking ensuring only one thread is in the critical
5//! section at any given point in time by blocking the others.
96//!
10//! {
11//! m.lock();
12//! defer m.unlock();
13//! // ... critical section code
14//! }
15//!
16//! if (m.tryLock()) {
17//! defer m.unlock();
18//! // ... critical section code
19//! }
20//! ```
7//! Mutex can be statically initialized and is at most `@sizeOf(u64)` large.
8//! Use `lock()` or `tryLock()` to enter the critical section and `unlock()` to leave it.
219
2210const std = @import("../std.zig");
2311const builtin = @import("builtin");
......@@ -30,6 +18,8 @@ const Futex = Thread.Futex;
3018
3119impl: Impl = .{},
3220
21pub const Recursive = @import("Mutex/Recursive.zig");
22
3323/// Tries to acquire the mutex without blocking the caller's thread.
3424/// Returns `false` if the calling thread would have to block to acquire it.
3525/// Otherwise, returns `true` and the caller should `unlock()` the Mutex to release it.
......@@ -312,3 +302,19 @@ test "many contended" {
312302
313303 try testing.expectEqual(runner.counter.get(), num_increments * num_threads);
314304}
305
306// https://github.com/ziglang/zig/issues/19295
307//test @This() {
308// var m: Mutex = .{};
309//
310// {
311// m.lock();
312// defer m.unlock();
313// // ... critical section code
314// }
315//
316// if (m.tryLock()) {
317// defer m.unlock();
318// // ... critical section code
319// }
320//}
lib/std/Thread/Mutex/Recursive.zig created+86
......@@ -0,0 +1,86 @@
1//! A synchronization primitive enforcing atomic access to a shared region of
2//! code known as the "critical section".
3//!
4//! Equivalent to `std.Mutex` except it allows the same thread to obtain the
5//! lock multiple times.
6//!
7//! A recursive mutex is an abstraction layer on top of a regular mutex;
8//! therefore it is recommended to use instead `std.Mutex` unless there is a
9//! specific reason a recursive mutex is warranted.
10
11const std = @import("../../std.zig");
12const Recursive = @This();
13const Mutex = std.Thread.Mutex;
14const assert = std.debug.assert;
15
16mutex: Mutex,
17thread_id: std.Thread.Id,
18lock_count: usize,
19
20pub const init: Recursive = .{
21 .mutex = .{},
22 .thread_id = invalid_thread_id,
23 .lock_count = 0,
24};
25
26/// Acquires the `Mutex` without blocking the caller's thread.
27///
28/// Returns `false` if the calling thread would have to block to acquire it.
29///
30/// Otherwise, returns `true` and the caller should `unlock()` the Mutex to release it.
31pub fn tryLock(r: *Recursive) bool {
32 const current_thread_id = std.Thread.getCurrentId();
33 return tryLockInner(r, current_thread_id);
34}
35
36/// Acquires the `Mutex`, blocking the current thread while the mutex is
37/// already held by another thread.
38///
39/// The `Mutex` can be held multiple times by the same thread.
40///
41/// Once acquired, call `unlock` on the `Mutex` to release it, regardless
42/// of whether the lock was already held by the same thread.
43pub fn lock(r: *Recursive) void {
44 const current_thread_id = std.Thread.getCurrentId();
45 if (!tryLockInner(r, current_thread_id)) {
46 r.mutex.lock();
47 assert(r.lock_count == 0);
48 r.lock_count = 1;
49 @atomicStore(std.Thread.Id, &r.thread_id, current_thread_id, .monotonic);
50 }
51}
52
53/// Releases the `Mutex` which was previously acquired with `lock` or `tryLock`.
54///
55/// It is undefined behavior to unlock from a different thread that it was
56/// locked from.
57pub fn unlock(r: *Recursive) void {
58 r.lock_count -= 1;
59 if (r.lock_count == 0) {
60 // Prevent race where:
61 // * Thread A obtains lock and has not yet stored the new thread id.
62 // * Thread B loads the thread id after tryLock() false and observes stale thread id.
63 @atomicStore(std.Thread.Id, &r.thread_id, invalid_thread_id, .seq_cst);
64 r.mutex.unlock();
65 }
66}
67
68fn tryLockInner(r: *Recursive, current_thread_id: std.Thread.Id) bool {
69 if (r.mutex.tryLock()) {
70 assert(r.lock_count == 0);
71 r.lock_count = 1;
72 @atomicStore(std.Thread.Id, &r.thread_id, current_thread_id, .monotonic);
73 return true;
74 }
75
76 const locked_thread_id = @atomicLoad(std.Thread.Id, &r.thread_id, .monotonic);
77 if (locked_thread_id == current_thread_id) {
78 r.lock_count += 1;
79 return true;
80 }
81
82 return false;
83}
84
85/// A value that does not alias any other thread id.
86const invalid_thread_id: std.Thread.Id = 0;