2 * Copyright 2015 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "include/private/SkSemaphore.h"
9 #include "src/core/SkLeanWindows.h"
11 #if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
12 #include <dispatch/dispatch.h>
14 struct SkSemaphore::OSSemaphore {
15 dispatch_semaphore_t fSemaphore;
17 OSSemaphore() { fSemaphore = dispatch_semaphore_create(0/*initial count*/); }
18 ~OSSemaphore() { dispatch_release(fSemaphore); }
20 void signal(int n) { while (n --> 0) { dispatch_semaphore_signal(fSemaphore); } }
21 void wait() { dispatch_semaphore_wait(fSemaphore, DISPATCH_TIME_FOREVER); }
23 #elif defined(SK_BUILD_FOR_WIN)
24 struct SkSemaphore::OSSemaphore {
28 fSemaphore = CreateSemaphore(nullptr /*security attributes, optional*/,
30 MAXLONG /*max count*/,
31 nullptr /*name, optional*/);
33 ~OSSemaphore() { CloseHandle(fSemaphore); }
36 ReleaseSemaphore(fSemaphore, n, nullptr/*returns previous count, optional*/);
38 void wait() { WaitForSingleObject(fSemaphore, INFINITE/*timeout in ms*/); }
41 // It's important we test for Mach before this. This code will compile but not work there.
43 #include <semaphore.h>
44 struct SkSemaphore::OSSemaphore {
47 OSSemaphore() { sem_init(&fSemaphore, 0/*cross process?*/, 0/*initial count*/); }
48 ~OSSemaphore() { sem_destroy(&fSemaphore); }
50 void signal(int n) { while (n --> 0) { sem_post(&fSemaphore); } }
52 // Try until we're not interrupted.
53 while(sem_wait(&fSemaphore) == -1 && errno == EINTR);
58 ///////////////////////////////////////////////////////////////////////////////
60 SkSemaphore::~SkSemaphore() {
64 void SkSemaphore::osSignal(int n) {
65 fOSSemaphoreOnce([this] { fOSSemaphore = new OSSemaphore; });
66 fOSSemaphore->signal(n);
69 void SkSemaphore::osWait() {
70 fOSSemaphoreOnce([this] { fOSSemaphore = new OSSemaphore; });
74 bool SkSemaphore::try_wait() {
75 int count = fCount.load(std::memory_order_relaxed);
77 return fCount.compare_exchange_weak(count, count-1, std::memory_order_acquire);