xref: /aosp_15_r20/external/cronet/base/task/thread_pool/semaphore/semaphore_apple.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2023 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // This file is a clone of "v8/src/base/platform/semaphore.cc" in v8.
6 // Keep in sync, especially when fixing bugs.
7 
8 // Copyright 2013 the V8 project authors. All rights reserved.
9 // Use of this source code is governed by a BSD-style license that can be
10 // found in the LICENSE file.
11 
12 #include "base/task/thread_pool/semaphore.h"
13 
14 #include <dispatch/dispatch.h>
15 
16 #include "base/check.h"
17 #include "base/time/time.h"
18 
19 namespace base {
20 namespace internal {
21 
Semaphore(int count)22 Semaphore::Semaphore(int count) {
23   native_handle_ = dispatch_semaphore_create(count);
24   CHECK(native_handle_);
25 }
26 
~Semaphore()27 Semaphore::~Semaphore() {
28   dispatch_release(native_handle_);
29 }
30 
Signal()31 void Semaphore::Signal() {
32   dispatch_semaphore_signal(native_handle_);
33 }
34 
Wait()35 void Semaphore::Wait() {
36   CHECK_EQ(dispatch_semaphore_wait(native_handle_, DISPATCH_TIME_FOREVER), 0);
37 }
38 
TimedWait(TimeDelta timeout)39 bool Semaphore::TimedWait(TimeDelta timeout) {
40   const dispatch_time_t wait_time =
41       timeout.is_max()
42           ? DISPATCH_TIME_FOREVER
43           : dispatch_time(DISPATCH_TIME_NOW, timeout.InNanoseconds());
44   return dispatch_semaphore_wait(native_handle_, wait_time) == 0;
45 }
46 
47 }  // namespace internal
48 }  // namespace base
49