AWS SDK for C++

AWS SDK for C++ Version 1.11.440

Loading...
Searching...
No Matches
ResourceManager.h
1
5#pragma once
6
7#include <aws/core/utils/memory/stl/AWSVector.h>
8#include <mutex>
9#include <condition_variable>
10#include <atomic>
11#include <cassert>
12
13namespace Aws
14{
15 namespace Utils
16 {
25 template< typename RESOURCE_TYPE>
27 {
28 public:
29 ExclusiveOwnershipResourceManager() : m_shutdown(false) {}
30
37 RESOURCE_TYPE Acquire()
38 {
39 std::unique_lock<std::mutex> locker(m_queueLock);
40 while(!m_shutdown.load() && m_resources.size() == 0)
41 {
42 m_semaphore.wait(locker, [&](){ return m_shutdown.load() || m_resources.size() > 0; });
43 }
44
45 assert(!m_shutdown);
46
47 RESOURCE_TYPE resource = m_resources.back();
48 m_resources.pop_back();
49
50 return resource;
51 }
52
59 RESOURCE_TYPE TryAcquire(typename std::enable_if<std::is_pointer<RESOURCE_TYPE>::value >::type* = 0)
60 {
61 std::unique_lock<std::mutex> locker(m_queueLock);
62 while(!m_shutdown.load() && m_resources.size() == 0)
63 {
64 m_semaphore.wait(locker, [&](){ return m_shutdown.load() || m_resources.size() > 0; });
65 }
66
67 if (m_shutdown) {
68 return nullptr;
69 }
70
71 RESOURCE_TYPE resource = m_resources.back();
72 m_resources.pop_back();
73
74 return resource;
75 }
76
84 {
85 std::lock_guard<std::mutex> locker(m_queueLock);
86 return m_resources.size() > 0 && !m_shutdown.load();
87 }
88
94 void Release(RESOURCE_TYPE resource)
95 {
96 std::unique_lock<std::mutex> locker(m_queueLock);
97 m_resources.push_back(resource);
98 locker.unlock();
99 m_semaphore.notify_one();
100 }
101
107 void PutResource(RESOURCE_TYPE resource)
108 {
109 m_resources.push_back(resource);
110 }
111
122 {
123 std::unique_lock<std::mutex> locker(m_queueLock);
124 m_shutdown = true;
125
126 //wait for all acquired resources to be released.
127 while (m_resources.size() < resourceCount)
128 {
129 m_semaphore.wait(locker, [&]() { return m_resources.size() == resourceCount; });
130 }
131
132 Aws::Vector<RESOURCE_TYPE> resources{std::move(m_resources)};
133 m_semaphore.notify_one();
134 return resources;
135 }
136
137 private:
138 Aws::Vector<RESOURCE_TYPE> m_resources;
139 std::mutex m_queueLock;
140 std::condition_variable m_semaphore;
141 std::atomic<bool> m_shutdown;
142 };
143 }
144}
Aws::Vector< RESOURCE_TYPE > ShutdownAndWait(size_t resourceCount)
RESOURCE_TYPE TryAcquire(typename std::enable_if< std::is_pointer< RESOURCE_TYPE >::value >::type *=0)
std::vector< T, Aws::Allocator< T > > Vector
Definition AWSVector.h:17