1 | /* |
---|---|
2 | * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
3 | * |
4 | * Licensed under the Apache License, Version 2.0 (the "License"). |
5 | * You may not use this file except in compliance with the License. |
6 | * A copy of the License is located at |
7 | * |
8 | * http://aws.amazon.com/apache2.0 |
9 | * |
10 | * or in the "license" file accompanying this file. This file is distributed |
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either |
12 | * express or implied. See the License for the specific language governing |
13 | * permissions and limitations under the License. |
14 | */ |
15 | |
16 | #include <aws/core/utils/threading/Semaphore.h> |
17 | #include <algorithm> |
18 | |
19 | using namespace Aws::Utils::Threading; |
20 | |
21 | Semaphore::Semaphore(size_t initialCount, size_t maxCount) |
22 | : m_count(initialCount), m_maxCount(maxCount) |
23 | { |
24 | } |
25 | |
26 | void Semaphore::WaitOne() |
27 | { |
28 | std::unique_lock<std::mutex> locker(m_mutex); |
29 | if(0 == m_count) |
30 | { |
31 | m_syncPoint.wait(locker, [this] { return m_count > 0; }); |
32 | } |
33 | --m_count; |
34 | } |
35 | |
36 | void Semaphore::Release() |
37 | { |
38 | std::lock_guard<std::mutex> locker(m_mutex); |
39 | m_count = (std::min)(m_maxCount, m_count + 1); |
40 | m_syncPoint.notify_one(); |
41 | } |
42 | |
43 | void Semaphore::ReleaseAll() |
44 | { |
45 | std::lock_guard<std::mutex> locker(m_mutex); |
46 | m_count = m_maxCount; |
47 | m_syncPoint.notify_all(); |
48 | } |
49 | |
50 |