diff options
| author | Andrew Kelley <andrew@ziglang.org> | 2021-01-14 20:41:37 -0700 |
|---|---|---|
| committer | Andrew Kelley <andrew@ziglang.org> | 2021-01-14 20:41:37 -0700 |
| commit | a9667b5a859a589056f23df2b74b91fede0bbbfa (patch) | |
| tree | 0efb150c8b3357b61f2dc11b0018a1038fe6d354 /lib/std/Thread/Semaphore.zig | |
| parent | 2b0e3ee228e01473cf880f719db9bde5b8f34d25 (diff) | |
| download | zig-a9667b5a859a589056f23df2b74b91fede0bbbfa.tar.gz zig-a9667b5a859a589056f23df2b74b91fede0bbbfa.zip | |
organize std lib concurrency primitives and add RwLock
* move concurrency primitives that always operate on kernel threads to
the std.Thread namespace
* remove std.SpinLock. Nobody should use this in a non-freestanding
environment; the other primitives are always preferable. In
freestanding, it will be necessary to put custom spin logic in there,
so there are no use cases for a std lib version.
* move some std lib files to the top level fields convention
* add std.Thread.spinLoopHint
* add std.Thread.Condition
* add std.Thread.Semaphore
* new implementation of std.Thread.Mutex for Windows and non-pthreads Linux
* add std.Thread.RwLock
Implementations provided by @kprotty
Diffstat (limited to 'lib/std/Thread/Semaphore.zig')
| -rw-r--r-- | lib/std/Thread/Semaphore.zig | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/lib/std/Thread/Semaphore.zig b/lib/std/Thread/Semaphore.zig new file mode 100644 index 0000000000..77a278b355 --- /dev/null +++ b/lib/std/Thread/Semaphore.zig @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2015-2021 Zig Contributors +// This file is part of [zig](https://ziglang.org/), which is MIT licensed. +// The MIT license requires this copyright notice to be included in all copies +// and substantial portions of the software. + +//! A semaphore is an unsigned integer that blocks the kernel thread if +//! the number would become negative. +//! This API supports static initialization and does not require deinitialization. + +mutex: Mutex = .{}, +cond: Condition = .{}, +//! It is OK to initialize this field to any value. +permits: usize = 0, + +const RwLock = @This(); +const std = @import("../std.zig"); +const Mutex = std.Thread.Mutex; +const Condition = std.Thread.Condition; + +pub fn wait(sem: *Semaphore) void { + const held = sem.mutex.acquire(); + defer held.release(); + + while (sem.permits == 0) + sem.cond.wait(&sem.mutex); + + sem.permits -= 1; + if (sem.permits > 0) + sem.cond.signal(); +} + +pub fn post(sem: *Semaphore) void { + const held = sem.mutex.acquire(); + defer held.release(); + + sem.permits += 1; + sem.cond.signal(); +} |
