1//
2// Semaphore.cpp
3//
4// Library: Foundation
5// Package: Threading
6// Module: Semaphore
7//
8// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
9// and Contributors.
10//
11// SPDX-License-Identifier: BSL-1.0
12//
13
14
15#include "Poco/Semaphore.h"
16#include <system_error>
17
18
19namespace Poco {
20
21
22Semaphore::Semaphore(int n): _count(n), _max(n)
23{
24 poco_assert (n >= 0);
25}
26
27
28Semaphore::Semaphore(int n, int max): _count(n), _max(max)
29{
30 poco_assert (n >= 0 && max > 0 && n <= max);
31}
32
33
34Semaphore::~Semaphore()
35{
36}
37
38
39void Semaphore::set()
40{
41 try
42 {
43 {
44 std::lock_guard<std::mutex> lock{_mutex};
45 if (_count < _max) ++_count;
46 }
47 _cv.notify_one();
48 }
49 catch (std::system_error &e)
50 {
51 throw SystemException(e.what());
52 }
53}
54
55
56void Semaphore::wait()
57{
58 try
59 {
60 std::unique_lock<std::mutex> lock{ _mutex };
61 _cv.wait(lock, [&] { return _count > 0; });
62 --_count;
63 }
64 catch (std::system_error &e)
65 {
66 throw SystemException(e.what());
67 }
68}
69
70
71bool Semaphore::waitImpl(long milliseconds)
72{
73 try
74 {
75 std::unique_lock<std::mutex> lock{ _mutex };
76 auto finished = _cv.wait_for(lock, std::chrono::milliseconds(milliseconds), [&] { return _count > 0; });
77 if (finished) --_count;
78 return finished;
79 }
80 catch (std::system_error &e)
81 {
82 throw SystemException(e.what());
83 }
84}
85
86
87} // namespace Poco
88