1 // Copyright 2013 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef V8_BASE_PLATFORM_SEMAPHORE_H_
6 #define V8_BASE_PLATFORM_SEMAPHORE_H_
8 #include "src/base/lazy-instance.h"
10 #include "src/base/win32-headers.h"
14 #include <mach/semaphore.h> // NOLINT
16 #include <semaphore.h> // NOLINT
22 // Forward declarations.
25 // ----------------------------------------------------------------------------
28 // A semaphore object is a synchronization object that maintains a count. The
29 // count is decremented each time a thread completes a wait for the semaphore
30 // object and incremented each time a thread signals the semaphore. When the
31 // count reaches zero, threads waiting for the semaphore blocks until the
32 // count becomes non-zero.
34 class Semaphore final {
36 explicit Semaphore(int count);
39 // Increments the semaphore counter.
42 // Suspends the calling thread until the semaphore counter is non zero
43 // and then decrements the semaphore counter.
46 // Suspends the calling thread until the counter is non zero or the timeout
47 // time has passed. If timeout happens the return value is false and the
48 // counter is unchanged. Otherwise the semaphore counter is decremented and
50 bool WaitFor(const TimeDelta& rel_time) WARN_UNUSED_RESULT;
53 typedef semaphore_t NativeHandle;
55 typedef sem_t NativeHandle;
57 typedef HANDLE NativeHandle;
60 NativeHandle& native_handle() {
61 return native_handle_;
63 const NativeHandle& native_handle() const {
64 return native_handle_;
68 NativeHandle native_handle_;
70 DISALLOW_COPY_AND_ASSIGN(Semaphore);
74 // POD Semaphore initialized lazily (i.e. the first time Pointer() is called).
76 // // The following semaphore starts at 0.
77 // static LazySemaphore<0>::type my_semaphore = LAZY_SEMAPHORE_INITIALIZER;
79 // void my_function() {
80 // // Do something with my_semaphore.Pointer().
85 struct CreateSemaphoreTrait {
86 static Semaphore* Create() {
87 return new Semaphore(N);
92 struct LazySemaphore {
93 typedef typename LazyDynamicInstance<Semaphore, CreateSemaphoreTrait<N>,
94 ThreadSafeInitOnceTrait>::type type;
97 #define LAZY_SEMAPHORE_INITIALIZER LAZY_DYNAMIC_INSTANCE_INITIALIZER
102 #endif // V8_BASE_PLATFORM_SEMAPHORE_H_