-
Notifications
You must be signed in to change notification settings - Fork 12
/
semaphore.cpp
48 lines (37 loc) · 1.24 KB
/
semaphore.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
////////////////////////////////////////////////////////////////////////////////
// Distributed under the Boost Software License, Version 1.0. //
// (See accompanying file LICENSE or copy at //
// https://www.boost.org/LICENSE_1_0.txt) //
////////////////////////////////////////////////////////////////////////////////
#include "core/semaphore.h"
#include <cstdint>
#include <memory>
#include <dispatch/dispatch.h>
#include "core/auto_release.h"
namespace iris
{
struct Semaphore::implementation
{
AutoRelease<::dispatch_semaphore_t, nullptr> semaphore;
std::atomic<std::ptrdiff_t> count;
};
Semaphore::Semaphore(std::ptrdiff_t initial)
: impl_(std::make_unique<implementation>())
{
impl_->semaphore = {::dispatch_semaphore_create(initial), ::dispatch_release};
impl_->count = initial;
}
Semaphore::~Semaphore() = default;
Semaphore::Semaphore(Semaphore &&) = default;
Semaphore &Semaphore::operator=(Semaphore &&) = default;
void Semaphore::release()
{
++impl_->count;
::dispatch_semaphore_signal(impl_->semaphore);
}
void Semaphore::acquire()
{
::dispatch_semaphore_wait(impl_->semaphore, DISPATCH_TIME_FOREVER);
--impl_->count;
}
}