├── README.md ├── LICENSE └── BlockingCollection.h /README.md: -------------------------------------------------------------------------------- 1 | # BlockingCollection 2 | BlockingCollection is a C++11 thread safe collection class that provides the following features: 3 | - Modeled after .NET BlockingCollection class. 4 | - Implementation of classic Producer/Consumer pattern (i.e. condition variable, mutex); 5 | - Adding and taking of items from multiple threads. 6 | - Optional maximum capacity. 7 | - Insertion and removal operations that block when collection is empty or full. 8 | - Insertion and removal "try" operations that do not block or that block up to a specified period of time. 9 | - Insertion and removal 'bulk" operations that allow more than one element to be added or taken at once. 10 | - Priority-based insertion and removal operations. 11 | - Encapsulates any collection type that satisfy the ProducerConsumerCollection requirement. 12 | - [Minimizes](#performance-optimizations) sleeps, wake ups and lock contention by managing an active subset of producer and consumer threads. 13 | - Pluggable condition variable and lock types. 14 | - Range-based loop support. 15 | 16 | ## Bounding and Blocking Support 17 | BlockingCollection supports bounding and blocking. Bounding means that you can set the maximum capacity 18 | of the collection. Bounding is important in certain scenarios because it enables you to control the maximum 19 | size of the collection in memory, and it prevents the producing threads from moving too far ahead of the consuming threads. 20 | 21 | Multiple threads or tasks can add elements to the collection, and if the collection reaches its specified maximum capacity, the producing threads will block until an element is removed. Multiple consumers can remove elements, and if the collection becomes empty, the consuming threads will block until a producer adds an item. A producing thread can call the complete_adding method to indicate that no more elements will be added. Consumers monitor the is_completed property to know when the collection is empty and no more elements will be added. The following example shows a simple BlockingCollection with a bounded capacity of 100. A producer task adds items to the collection as long as some external condition is true, and then calls complete_adding. The consumer task takes items until the is_completed property is true. 22 | ```C++ 23 | // A bounded collection. It can hold no more 24 | // than 100 items at once. 25 | BlockingCollection collection(100); 26 | 27 | // a simple blocking consumer 28 | std::thread consumer_thread([&collection]() { 29 | 30 | while (!collection.is_completed()) 31 | { 32 | Data* data; 33 | 34 | // take will block if there is no data to be taken 35 | auto status = collection.take(data); 36 | 37 | if(status == BlockingCollectionStatus::Ok) 38 | { 39 | process(data); 40 | } 41 | 42 | // Status can also return BlockingCollectionStatus::Completed meaning take was called 43 | // on a completed collection. Some other thread can call complete_adding after we pass 44 | // the is_completed check but before we call take. In this example, we can ignore that 45 | // status since the loop will break on the next iteration. 46 | } 47 | }); 48 | 49 | // a simple blocking producer 50 | std::thread producer_thread([&collection]() { 51 | 52 | while (moreItemsToAdd) 53 | { 54 | Data* data = GetData(data); 55 | 56 | // blocks if collection.size() == collection.bounded_capacity() 57 | collection.add(data); 58 | } 59 | 60 | // let consumer know we are done 61 | collection.complete_adding(); 62 | }); 63 | ``` 64 | ## Timed Blocking Operations 65 | In timed blocking try_add and try_take operations on bounded collections, the method tries to add or take an item. If an item is available it is placed into the variable that was passed in by reference, and the method returns Ok. If no item is retrieved after a specified time-out period the method returns TimedOut. The thread is then free to do some other useful work before trying again to access the collection. 66 | ```C++ 67 | BlockingCollection collection(100); 68 | 69 | Data *data; 70 | 71 | // if the collection is empty this method returns immediately 72 | auto status = collection.try_take(data); 73 | 74 | // if the collection is still empty after 1 sec this method returns immediately 75 | status = collection.try_take(data, std::chrono::milliseconds(1000)); 76 | 77 | // in both case status will return BlockingCollectionStatus::TimedOut if 78 | // try_take times out waiting for data to become available 79 | ``` 80 | ## Bulk Operations 81 | BlockingCollection's add and take operations are all thread safe. But it accomplishes this by using a mutex. To minimize mutex contention when adding or taking elements BlockingCollection supports bulk operations. It is usually much cheaper to acquire the mutex and then to add or take a whole batch of elements in one go, than it is to acquire and release the mutex for every add and take. 82 | ```C++ 83 | BlockingCollection collection(100); 84 | 85 | std::array arr; 86 | 87 | size_t taken; 88 | 89 | auto status = collection.try_take_bulk(arr, arr.size(), taken); 90 | 91 | // try_take_bulk will update taken with actual number of items taken 92 | ``` 93 | ## Specifying the Collection Type 94 | When you create a BlockingCollection object, you can specify not only the bounded capacity but also the type of collection to use. 95 | For example, you could specify a ```QueueContainer``` object for first in, first out (FIFO) behavior, or a ```StackContainer``` object for last in, first out (LIFO) behavior. You can use any collection class that supports the ProducerConsumerCollection requirement. The default collection type for BlockingCollection is ```QueueContainer```. The following code example shows how to create a BlockingCollection of strings that has a capacity of 1000 and uses a ```StackContainer``` 96 | ```C++ 97 | BlockingCollection> stack(1000); 98 | ``` 99 | Type aliases are also available: 100 | ```C++ 101 | BlockingQueue blocking_queue; 102 | BlockingStack blocking_stack; 103 | ``` 104 | ## Priority based Insertion and Removal 105 | PriorityBlockingCollection offers the same functionality found in BlockingCollection. 106 | But the add/try_add methods add items to the collection based on their priority - (0 is lowest priority). 107 | 108 | FIFO order is maintained when items of the same priority are added consecutively. And the take/try_take methods 109 | return the highest priority items in FIFO order. 110 | 111 | In addition, PriorityBlockingCollection adds additional methods (i.e. take_prio/try_take_prio) for taking 112 | the lowest priority items. 113 | 114 | PriorityBlockingCollection's default priority comparer expects that the objects being compared have 115 | overloaded < and > operators. If this is not the case then you can provide your own comparer implementation 116 | like in the following example. 117 | ```C++ 118 | struct PriorityItem { 119 | PriorityItem(int priority) : Priority(priority) 120 | {} 121 | 122 | int Priority; 123 | }; 124 | 125 | class CustomComparer { 126 | public: 127 | CustomComparer() { 128 | } 129 | 130 | int operator() (const PriorityItem &item, const PriorityItem &new_item) { 131 | if (item.Priority < new_item.Priority) 132 | return -1; 133 | else if (item.Priority > new_item.Priority) 134 | return 1; 135 | else 136 | return 0; 137 | } 138 | }; 139 | 140 | using CustomPriorityContainer = PriorityContainer; 141 | 142 | PriorityBlockingCollection collection; 143 | ``` 144 | ## Range-based for loop Support 145 | BlockingCollection provides an iterator that enables consumers to use ```for(auto item : collection) { ... }```to remove items until the collection is completed, which means it is empty and no more items will be added. For more information, see 146 | ```C++ 147 | BlockingCollection collection(100); 148 | 149 | // a simple blocking consumer using range-base loop 150 | std::thread consumer_thread([&collection]() { 151 | 152 | for(auto data : collection) { 153 | process(data); 154 | } 155 | }); 156 | ``` 157 | ## ProducerConsumerCollection Requirement 158 | In order for a container to be used with the BlockingCollection it must meet the ProducerConsumerCollection requirement. 159 | The ProducerConsumerCollection requires that all the following method signatures must be supported: 160 | 161 | - size_type size() 162 | - bool try_add(const value_type& element) 163 | - bool try_add(value_type&& element) 164 | - bool try_take(value_type& element) 165 | - template bool try_emplace(Args&&... args) 166 | 167 | BlockingCollection currently supports three containers: 168 | 169 | - QueueContainer 170 | - StackContainer 171 | - PriorityContainer 172 | 173 | ## Performance Optimizations 174 | BlockingCollection can behave like most condition variable based collections. That is, it will by default issue a signal each time a element is added or taken from its underlying Container. But this approach leads to poor application scaling and performance. 175 | 176 | So in the interest of performance BlockingCollection can be configured to maintain a subset of active threads that are currently adding and taking elements. This is important because it allows BlockingCollection not to have to issue a signal each time an element is added or taken. Instead in the case of consumers it issues a signal only when an element is taken and there are no active consumers, or when the Container's element count starts to grow beyond a threshold level. And in the case of producers, BlockingCollection will issue a signal only when an element is added and there are no active producers or when the Container's available capacity starts to grow beyond a threshold level. 177 | 178 | In both cases, this approach greatly improves performance and makes it more predictable. 179 | 180 | Two strategy classes are responsible for implementing the behavior just described. 181 | 182 | 1. NotEmptySignalStrategy 183 | - implements conditions under which a "not empty" condition variable should issue a signal 184 | 185 | 2. NotFullSignalStrategy 186 | - implements conditions under which a "not full" condition variable should issue a signal 187 | 188 | ### NotEmptySignalStrategy 189 | This strategy will return true under two conditions. 190 | 191 | 1. All consumers are currently not active (i.e. waiting) 192 | 2. Number of active consumers < total consumers AND number of item in collection per active consumer is > threshold value 193 | ```C++ 194 | template struct NotEmptySignalStrategy { 195 | 196 | bool should_signal(size_t active_workers, size_t total_workers, size_t item_count, size_t /*capacity*/) const { 197 | return active_workers == 0 || (active_workers < total_workers && item_count / active_workers > ItemsPerThread); 198 | } 199 | }; 200 | ``` 201 | ### NotFullSignalStrategy 202 | This strategy will return true under two conditions. 203 | 204 | 1. All producers are currently not active (i.e. waiting) 205 | 2. Number of active producers < total producers AND current available capacity per active producer is > threshold value 206 | ```C++ 207 | template struct NotFullSignalStrategy { 208 | 209 | bool should_signal(size_t active_workers, size_t total_workers, size_t item_count, size_t capacity) const { 210 | return (active_workers == 0 || (active_workers < total_workers && (capacity - item_count) / active_workers > ItemsPerThread)); 211 | } 212 | }; 213 | ``` 214 | Note that in both strategies the threshold value (i.e. ItemsPerThread) can be specified. And that completely new strategies can be used for both "no empty" and "not full" use cases by creating a new strategy that implements the required method signature. 215 | ```C++ 216 | bool should_signal(size_t active_workers, size_t total_workers, size_t item_count, size_t capacity) 217 | ``` 218 | ### Attaching/Detaching Consumers & Producers 219 | In order for BlockingCollection to maintain a subset of active threads it exposes attach_producer and attach_consumer member function. The calling thread can call either of those functions to attach itself to the BlockingCollection as either a producer or consumer respectively. Note that the thread should remember to detach itself in both cases. 220 | ```C++ 221 | BlockingCollection collection(100); 222 | 223 | std::thread consumer_thread([&collection]() { 224 | 225 | collection.attach_consumer(); 226 | 227 | int item; 228 | 229 | for(int i = 0; i < 10; i++) 230 | collection.take(item); 231 | 232 | collection.detach_consumer(); 233 | }); 234 | ``` 235 | ### Consumer & Producer Guards 236 | In order to mitigate forgetting to attach or detach from a BlockingCollection the BlockingCollection Guard classes (i.e. ProducerGuard and ConsumerGuard) can be used for this purpose. Both Guard classes are a RAII-style mechanism for attaching a thread to the BlockingCollection and detaching it when the thread terminates. As well as in exception scenarios. 237 | 238 | In the following examples, ConsumerGuard and ProducerGuard automatically attach and detach the std::threads to the BlockingCollection. 239 | ```C++ 240 | BlockingCollection collection; 241 | 242 | std::thread consumer_thread([&collection]() { 243 | 244 | ConsumerGuard> Guard(collection); 245 | 246 | int item; 247 | 248 | for(int i = 0; i < 10; i++) 249 | collection.take(item); 250 | }); 251 | ``` 252 | ```C++ 253 | std::thread producer_thread([&collection]() { 254 | 255 | ProducerGuard> Guard(collection); 256 | 257 | for(int i = 0; i < 10; i++) 258 | collection.add(i+1); 259 | }); 260 | ``` 261 | ## Pluggable Condition Variable and Lock Types 262 | The BlockingCollection class by default will use std::condition_variable and std::mutex classes. But those two synchronization primitives can be overridden by specializing ConditionVarTraits. 263 | ```C++ 264 | template 265 | struct ConditionVarTraits; 266 | 267 | template <> 268 | struct ConditionVarTraits 269 | { 270 | static void initialize(std::condition_variable& cond_var) { 271 | } 272 | 273 | static void signal(std::condition_variable& cond_var) { 274 | cond_var.notify_one(); 275 | } 276 | 277 | static void broadcast(std::condition_variable& cond_var) { 278 | cond_var.notify_all(); 279 | } 280 | 281 | static void wait(std::condition_variable& cond_var, std::unique_lock& lock) { 282 | cond_var.wait(lock); 283 | } 284 | 285 | template static bool wait_for(std::condition_variable& cond_var, std::unique_lock& lock, const std::chrono::duration& rel_time) { 286 | return std::cv_status::timeout == cond_var.wait_for(lock, rel_time); 287 | } 288 | }; 289 | ``` 290 | In the following example, ConditionVarTraits is specialized to use Win32 CONDITION_VARIABLE and SRW_LOCK. 291 | 292 | Note that Win32's SRWLOCK synchronization primitive requires a wrapper class so that it can meet the BasicLockable requirements needed by std::unique_lock. 293 | ```C++ 294 | class WIN32_SRWLOCK { 295 | public: 296 | WIN32_SRWLOCK() { 297 | InitializeSRWLock(&srw_); 298 | } 299 | 300 | void lock() { 301 | AcquireSRWLockExclusive(&srw_); 302 | } 303 | 304 | void unlock() { 305 | ReleaseSRWLockExclusive(&srw_); 306 | } 307 | 308 | SRWLOCK& native_handle() { 309 | return srw_; 310 | } 311 | private: 312 | SRWLOCK srw_; 313 | }; 314 | 315 | template <> 316 | struct ConditionVarTraits 317 | { 318 | static void initialize(CONDITION_VARIABLE& cond_var) { 319 | InitializeConditionVariable(&cond_var); 320 | } 321 | 322 | static void signal(CONDITION_VARIABLE& cond_var) { 323 | WakeConditionVariable(&cond_var); 324 | } 325 | 326 | static void broadcast(CONDITION_VARIABLE& cond_var) { 327 | WakeAllConditionVariable(&cond_var); 328 | } 329 | 330 | static void wait(CONDITION_VARIABLE& cond_var, std::unique_lock& lock) { 331 | SleepConditionVariableSRW(&cond_var, &lock.mutex()->native_handle(), INFINITE, 0); 332 | } 333 | 334 | template static bool wait_for(CONDITION_VARIABLE& cond_var, std::unique_lock& lock, const std::chrono::duration& rel_time) { 335 | 336 | DWORD milliseconds = static_cast(rel_time.count()); 337 | 338 | if (!SleepConditionVariableSRW(&cond_var, &lock.mutex()->native_handle(), milliseconds, 0)) { 339 | if (GetLastError() == ERROR_TIMEOUT) 340 | return true; 341 | } 342 | return false; 343 | } 344 | }; 345 | ``` 346 | ## Condition Variable Generator 347 | The BlockingCollection class uses the ConditionVariableGenerator template to generate the condition variable and lock types it will use. In addition, the template also generates the strategy classes. 348 | ```C++ 349 | template 350 | struct ConditionVariableGenerator { 351 | 352 | using NotFullType = ConditionVariable; 353 | using NotEmptyType = ConditionVariable; 354 | 355 | using lock_type = LockType; 356 | }; 357 | ``` 358 | By default, the BlockingCollection class will use the following ConditionVariableGenerator type alias. 359 | ```C++ 360 | using StdConditionVariableGenerator = ConditionVariableGenerator, NotFullSignalStrategy<16>, NotEmptySignalStrategy<16>, std::condition_variable, std::mutex>; 361 | ``` 362 | But it can easily be replaced by something else such as the following. 363 | ```C++ 364 | using Win32ConditionVariableGenerator = ConditionVariableGenerator, NotFullSignalStrategy<16>, NotEmptySignalStrategy<16>, CONDITION_VARIABLE, WIN32_SRWLOCK>; 365 | ``` 366 | A custom condition variable generator can be used like so: 367 | ```C++ 368 | BlockingCollection, Win32ConditionVariableGenerator> collection; 369 | ``` 370 | ## References 371 | 1. ^ [a](#bounding-and-blocking-support) [b](#timed-blocking-operations) [c](#specifying-the-collection-type) Microsoft Docs, *"BlockingCollection Overview"* [link](https://docs.microsoft.com/en-us/dotnet/standard/collections/thread-safe/blockingcollection-overview) 372 | 373 | BlockingCollection implements optimizations described in the following paper: 374 | 375 | [2007] Hewlett Packard Development Company, L.P *"Techniques for Improving the Scalability of Applications Using POSIX Thread Condition Variables"* [pdf](https://www.yumpu.com/en/document/view/18689696/making-condition-variables-perform-hp) 376 | 377 | ## License 378 | BlockingCollection uses the GPLv3 license that is available [here](https://github.com/CodeExMachina/BlockingCollection/blob/master/LICENSE). 379 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /BlockingCollection.h: -------------------------------------------------------------------------------- 1 | /// Copyright (c) 2018 Code Ex Machina, LLC. All rights reserved. 2 | /// 3 | /// This program is free software: you can redistribute it and/or modify 4 | /// it under the terms of the GNU General Public License as published by 5 | /// the Free Software Foundation, either version 3 of the License, or 6 | /// (at your option) any later version. 7 | /// 8 | /// This program is distributed in the hope that it will be useful, 9 | /// but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the 11 | /// GNU General Public License for more details. 12 | /// 13 | /// You should have received a copy of the GNU General Public License 14 | /// along with this program.If not, see . 15 | 16 | #ifndef BlockingCollection_h 17 | #define BlockingCollection_h 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | namespace code_machina { 28 | 29 | template 30 | struct ConditionVarTraits; 31 | 32 | template <> 33 | struct ConditionVarTraits { 34 | static void initialize(std::condition_variable& cond_var) { 35 | } 36 | 37 | static void signal(std::condition_variable& cond_var) { 38 | cond_var.notify_one(); 39 | } 40 | 41 | static void broadcast(std::condition_variable& cond_var) { 42 | cond_var.notify_all(); 43 | } 44 | 45 | static void wait(std::condition_variable& cond_var, 46 | std::unique_lock& lock) { 47 | cond_var.wait(lock); 48 | } 49 | 50 | template static bool wait_for( 51 | std::condition_variable& cond_var, 52 | std::unique_lock& lock, 53 | const std::chrono::duration& rel_time) { 54 | return std::cv_status::timeout == cond_var.wait_for(lock, rel_time); 55 | } 56 | }; 57 | 58 | /// @class ConditionVariable 59 | /// The ConditionVariable class wraps a operating system ConditionVariable. 60 | /// 61 | /// In addition, it implements support for attaching and detaching workers 62 | /// to the condition variable. 63 | /// @tparam ThreadContainerType The type of thread Container. 64 | /// @tparam SignalStrategyType The type of signal policy. 65 | /// @see NotEmptySignalStrategy 66 | /// @see NotFullSignalStrategy 67 | template 69 | class ConditionVariable { 70 | public: 71 | /// Initializes a new instance of the ConditionVariable class without an 72 | /// upper-bound. 73 | ConditionVariable() 74 | : total_workers_(0), active_workers_(0), bounded_capacity_(SIZE_MAX), 75 | item_count_(0) { 76 | ConditionVarTraits::initialize( 77 | condition_var_); 78 | } 79 | 80 | ~ConditionVariable() { 81 | } 82 | 83 | // "ConditionVariable" objects cannot be copied or assigned 84 | ConditionVariable(const ConditionVariable&) = delete; 85 | ConditionVariable& operator=(const ConditionVariable&) = delete; 86 | 87 | /// Gets the number of workers attached to this condition variable. 88 | /// @return The number of workers attached to this condition variable. 89 | /// @see Attach 90 | size_t total() const { 91 | return total_workers_; 92 | } 93 | 94 | /// Gets the number of active workers for this condition variable. 95 | /// active workers are workers that are currently NOT waiting on this 96 | /// condition variable. 97 | /// @return The number of active workers. 98 | size_t active() const { 99 | return active_workers_; 100 | } 101 | 102 | /// Gets the bounded capacity of this condition variable instance. 103 | /// @return The bounded capacity of this condition variable. 104 | size_t bounded_capacity() const { 105 | return bounded_capacity_; 106 | } 107 | 108 | /// Sets the bounded capacity of this condition variable instance. 109 | void bounded_capacity(size_t capacity) { 110 | bounded_capacity_ = capacity; 111 | } 112 | 113 | /// Gets the number of items contained in this condition variable 114 | /// instance. 115 | /// @return The number of items 116 | size_t size() const { 117 | return item_count_; 118 | } 119 | 120 | /// Set the number of items contained in this condition variable 121 | /// instance. 122 | void size(size_t count) { 123 | item_count_ = count; 124 | } 125 | 126 | /// Registers the a worker with this condition variable. 127 | /// If the worker is already registered then this method has no effect. 128 | /// @see Detach 129 | void attach() { 130 | if (container_.add()) { 131 | increment_total(); 132 | increment_active(); 133 | } 134 | } 135 | 136 | /// Unregisters the worker from this condition variable. 137 | /// If the worker was not previously registered then this method has 138 | /// no effect. 139 | /// @see Attach 140 | void detach() { 141 | if (container_.remove()) { 142 | decrement_total(); 143 | decrement_active(); 144 | } 145 | 146 | if (total_workers_ > 0 && active_workers_ == 0) { 147 | increment_active(); 148 | ConditionVarTraits::signal( 149 | condition_var_); 150 | } 151 | } 152 | 153 | /// Wakes up a worker waiting on this condition variable. 154 | void signal() { 155 | // if no workers attached always signal! 156 | if (total_workers_ == 0) { 157 | ConditionVarTraits::signal( 158 | condition_var_); 159 | return; 160 | } 161 | // issue a signal only when there are no active workers, or when 162 | // the count starts to grow beyond a threshold level 163 | if (signal_.should_signal(active_workers_, total_workers_, 164 | item_count_, bounded_capacity_)) { 165 | increment_active(); 166 | ConditionVarTraits::signal( 167 | condition_var_); 168 | } 169 | } 170 | 171 | /// Wakes up all workers waiting on this condition variable. 172 | void broadcast() { 173 | if (total_workers_ != 0) { 174 | // set active only if workers attached 175 | active(total_workers_); 176 | } 177 | ConditionVarTraits::broadcast( 178 | condition_var_); 179 | } 180 | 181 | /// Waits indefinitely for this condition variable to become signaled. 182 | /// @param lock An object of type std::unique_lock which must be locked 183 | /// by the current thread. 184 | void wait(std::unique_lock& lock) { 185 | decrement_active(); 186 | ConditionVarTraits::wait( 187 | condition_var_, lock); 188 | } 189 | 190 | /// Waits up to specified duration for this condition variable to become 191 | /// signaled. 192 | /// @param lock An object of type std::unique_lock which must be locked 193 | /// by the current thread. 194 | /// @param rel_time An object of type std::chrono::duration representing 195 | /// the maximum time to spend waiting. 196 | template bool wait_for( 197 | std::unique_lock& lock, 198 | const std::chrono::duration& rel_time) { 199 | decrement_active(); 200 | 201 | bool timed_out = 202 | ConditionVarTraits::wait_for( 203 | condition_var_, lock, rel_time); 204 | 205 | if (timed_out) { 206 | increment_active(); 207 | } 208 | 209 | return timed_out; 210 | } 211 | 212 | private: 213 | /// Sets the number of active workers for this condition variable. 214 | /// @param active The number of active workers. 215 | void active(size_t active) { 216 | active_workers_ = active > total_workers_ ? total_workers_ : active; 217 | } 218 | 219 | /// Increments the total worker count for this condition variable by 1. 220 | void increment_total() { 221 | total_workers_ += 1; 222 | } 223 | 224 | /// Decrements the total worker count for this condition variable by 1. 225 | void decrement_total() { 226 | total_workers_ = total_workers_ > 0 ? total_workers_ - 1 : 0; 227 | } 228 | 229 | /// Increments the active worker count for this condition variable by 1. 230 | void increment_active() { 231 | if (++active_workers_ > total_workers_) 232 | active_workers_ = total_workers_; 233 | } 234 | 235 | /// Decrements the active worker count for this condition variable by 1. 236 | void decrement_active() { 237 | active_workers_ = active_workers_ > 0 ? active_workers_ - 1 : 0; 238 | } 239 | 240 | size_t total_workers_; 241 | size_t active_workers_; 242 | size_t bounded_capacity_; 243 | size_t item_count_; 244 | 245 | ConditionVarType condition_var_; 246 | ThreadContainerType container_; 247 | SignalStrategyType signal_; 248 | }; 249 | 250 | /// @class NotEmptySignalStrategy 251 | /// 252 | /// A strategy object for determining whether or not a "not empty" condition 253 | /// variable should issue a signal. 254 | /// 255 | /// This strategy will only return true if there are no active workers 256 | /// (i.e. all workers are waiting 257 | /// on empty BlockingCollection). Or when the BlockingCollection's element 258 | /// count starts to grow beyond a 259 | /// threshold level. 260 | /// 261 | /// This approach minimizes condition variable sleeps, wakes and lock 262 | /// contention. Which in turn, 263 | /// improves performance and makes it more predictable. 264 | /// @tparam ItemsPerThread The number of items to allow per thread. 265 | /// @see ConditionVariable 266 | /// @see NotFullSignalStrategy 267 | template struct NotEmptySignalStrategy { 268 | bool should_signal(size_t active_workers, size_t total_workers, 269 | size_t item_count, size_t /*capacity*/) const { 270 | return active_workers == 0 || (active_workers < total_workers && 271 | item_count / active_workers > ItemsPerThread); 272 | } 273 | }; 274 | 275 | /// @class NotFullSignalStrategy 276 | /// 277 | /// A strategy object for determining whether or not a "not full" condition 278 | /// variable should issue a signal. 279 | /// 280 | /// This strategy will only return true if there are no active workers 281 | /// (i.e. all workers are 282 | /// waiting on a full BlockingCollection). Or when the BlockingCollection's 283 | /// available capacity 284 | /// starts to grow beyond a threshold level. 285 | /// 286 | /// This approach minimizes condition variable sleeps, wakes and lock 287 | /// contention. Which in turn, 288 | /// improves performance and makes it more predictable. 289 | /// @tparam ItemsPerThread The number of items to allow per thread. 290 | /// @see ConditionVariable 291 | /// @see NotEmptySignalStrategy 292 | template struct NotFullSignalStrategy { 293 | bool should_signal(size_t active_workers, size_t total_workers, 294 | size_t item_count, size_t capacity) const { 295 | return (active_workers == 0 || (active_workers < total_workers && 296 | (capacity - item_count) / active_workers > ItemsPerThread)); 297 | } 298 | }; 299 | 300 | /// @class ConditionVariableGenerator 301 | /// 302 | /// Generates the "not full" and "not empty" condition variables for 303 | /// the specified ThreadContainerType. 304 | /// 305 | /// @tparam ThreadContainerType The thread Container policy to use when 306 | /// generating the condition variables. 307 | template struct ConditionVariableGenerator { 310 | using NotFullType = ConditionVariable; 312 | using NotEmptyType = ConditionVariable; 314 | 315 | using lock_type = LockType; 316 | }; 317 | 318 | template 319 | struct ThreadContainerTraits; 320 | 321 | template <> 322 | struct ThreadContainerTraits { 323 | static std::thread::id get_thread_id() { 324 | return std::this_thread::get_id(); 325 | } 326 | }; 327 | 328 | /// @class ThreadContainer 329 | /// This class adds and removes the specified thread type from the 330 | /// Container. 331 | /// @tparam T The thread type. 332 | template class ThreadContainer { 333 | public: 334 | ThreadContainer() { 335 | } 336 | 337 | /// Adds the calling thread to the Container. 338 | /// @returns True if the calling thread was added to Container. 339 | /// Otherwise false. 340 | bool add() { 341 | T id = ThreadContainerTraits::get_thread_id(); 342 | 343 | typename std::unordered_set::iterator itr = thread_id_.find(id); 344 | 345 | if (itr != thread_id_.end()) { 346 | return false; 347 | } 348 | 349 | thread_id_.insert(id); 350 | return true; 351 | } 352 | 353 | /// Removes the calling thread from the Container. 354 | /// @returns True if the calling thread was removed from Container. 355 | /// Otherwise false. 356 | bool remove() { 357 | if (thread_id_.erase(ThreadContainerTraits::get_thread_id()) 358 | > 0) { 359 | return true; 360 | } 361 | return false; 362 | } 363 | 364 | private: 365 | std::unordered_set thread_id_; 366 | }; 367 | 368 | namespace detail { 369 | struct QueueType {}; 370 | struct StackType {}; 371 | 372 | template< typename T > 373 | struct is_queue : std::false_type { }; 374 | 375 | template<> 376 | struct is_queue : std::true_type {}; 377 | 378 | /// @class Container 379 | /// 380 | /// Represents a first in-first out (FIFO) or a last in-first out 381 | /// (LIFO) collection depending on 382 | /// the ContainerType template parameter value. 383 | /// 384 | /// Implements the implicitly defined IProducerConsumerCollection 385 | /// policy. 386 | /// @tparam T The type of items in the Container. 387 | /// @tparam ContainerType The type of Container (i.e. Queue or Stack). 388 | template 389 | class Container { 390 | public: 391 | using container_type = std::deque; 392 | using value_type = typename container_type::value_type; 393 | using size_type = typename container_type::size_type; 394 | 395 | /// Initializes a new instance of the Container class. 396 | Container() 397 | : bounded_capacity_(SIZE_MAX) { 398 | } 399 | 400 | /// Sets the max number of elements this container can hold. 401 | /// @param bounded_capacity The max number of elements this 402 | /// container can hold. 403 | void bounded_capacity(size_t bounded_capacity) { 404 | bounded_capacity_ = bounded_capacity; 405 | } 406 | 407 | /// Gets the max number of elements this container can hold. 408 | /// @returns The max number of elements this container can hold. 409 | size_t bounded_capacity() { 410 | return bounded_capacity_; 411 | } 412 | 413 | /// Gets the number of elements contained in the collection. 414 | /// @returns The number of elements contained in the collection. 415 | size_type size() { 416 | return container_.size(); 417 | } 418 | 419 | /// Attempts to add an element to the collection. 420 | /// @param item The element to add to the collection. 421 | /// @returns True if the element was added successfully; otherwise, 422 | /// false. 423 | bool try_add(const value_type& item) { 424 | if (container_.size() == bounded_capacity_) 425 | return false; 426 | container_.push_back(item); 427 | return true; 428 | } 429 | 430 | /// Attempts to add an element to the collection. 431 | /// @param item The element to add to the collection. 432 | /// @returns True if the element was added successfully; otherwise, 433 | /// false. 434 | bool try_add(value_type&& item) { 435 | if (container_.size() == bounded_capacity_) 436 | return false; 437 | container_.push_back(std::forward(item)); 438 | return true; 439 | } 440 | 441 | /// Attempts to remove and return an element from the collection. 442 | /// @param [out] item When this method returns, if the element was 443 | /// removed and returned successfully, item 444 | /// contains the removed element. If no element was available to be 445 | /// removed, the value is unspecified. 446 | /// @returns True if an element was removed and returned 447 | /// successfully; otherwise, false. 448 | bool try_take(value_type& item) { 449 | if (container_.empty()) 450 | return false; 451 | return try_take_i(item, is_queue()); 452 | } 453 | 454 | /// Attempts to add an element to the collection. 455 | /// This new element is constructed in place using args as the 456 | /// arguments for its construction. 457 | /// @param args Arguments forwarded to construct the new element. 458 | template bool try_emplace(Args&&... args) { 459 | if (container_.size() == bounded_capacity_) 460 | return false; 461 | return try_emplace_i(std::forward(args)..., 462 | is_queue()); 463 | } 464 | 465 | private: 466 | size_t bounded_capacity_; 467 | container_type container_; 468 | 469 | bool try_take_i(value_type& item, std::false_type) { 470 | item = container_.back(); 471 | container_.pop_back(); 472 | return true; 473 | } 474 | 475 | bool try_take_i(value_type& item, std::true_type) { 476 | item = container_.front(); 477 | container_.pop_front(); 478 | return true; 479 | } 480 | 481 | template bool try_emplace_i(Args&&... args, 482 | std::false_type) { 483 | container_.emplace_front(std::forward(args)...); 484 | return true; 485 | } 486 | 487 | template bool try_emplace_i(Args&&... args, 488 | std::true_type) { 489 | container_.emplace_back(std::forward(args)...); 490 | return true; 491 | } 492 | }; 493 | } // namespace detail 494 | 495 | template 496 | using QueueContainer = detail::Container; 497 | 498 | template 499 | using StackContainer = detail::Container; 500 | 501 | using StdConditionVariableGenerator = ConditionVariableGenerator< 502 | ThreadContainer, NotFullSignalStrategy<16>, 503 | NotEmptySignalStrategy<16>, std::condition_variable, std::mutex>; 504 | 505 | /// @enum BlockingCollectionState 506 | /// The BlockCollection states. 507 | enum class BlockingCollectionState { 508 | // BlockingCollection is active and processing normally. 509 | Activated = 1, 510 | // BlockingCollection is deactivated; no add or take operations allowed. 511 | Deactivated = 2, 512 | // BlockingCollection was pulsed; add and take may proceed normally. 513 | Pulsed = 3 514 | }; 515 | 516 | /// @enum BlockingCollectionStatus 517 | /// The BlockCollection status codes. 518 | /// These are the status codes returned by all of BlockingCollection's Add 519 | /// and Take operations. 520 | enum class BlockingCollectionStatus { 521 | /// Operation succeeded 522 | Ok = 0, 523 | /// Operation failed due to CompleteAdding() having been invoked 524 | AddingCompleted = -1, 525 | /// Operation failed due to time out 526 | TimedOut = -2, 527 | /// Operation failed due to BlockingCollection not being activated 528 | NotActivated = -3, 529 | /// Operation failed due to BlockingCollection being completed 530 | Completed = -4, 531 | /// Operation failed due to invalid iterators 532 | InvalidIterators = -5, 533 | /// Operation failed due to concurrent Add and CompleteAdding 534 | CompleteAddingConcurrent = -6, 535 | /// Operation failed due to BlockingCollection Container error 536 | InternalError = -8 537 | }; 538 | 539 | template , 540 | typename ConditionVariableGenerator = StdConditionVariableGenerator> 541 | class BlockingCollection { 542 | public: 543 | using LockType = typename ConditionVariableGenerator::lock_type; 544 | 545 | /// Initializes a new instance of the BlockingCollection class 546 | /// without an upper-bound. 547 | BlockingCollection() 548 | : BlockingCollection(SIZE_MAX) { 549 | } 550 | 551 | /// Initializes a new instance of the BlockingCollection class 552 | /// with the specified upper-bound. 553 | /// @param capacity The bounded size of the collection. 554 | explicit BlockingCollection(size_t capacity) 555 | : state_(BlockingCollectionState::Activated), 556 | bounded_capacity_(capacity), 557 | is_adding_completed_(false) { 558 | not_empty_condition_var_.bounded_capacity(capacity); 559 | not_full_condition_var_.bounded_capacity(capacity); 560 | container_.bounded_capacity(capacity); 561 | } 562 | 563 | // "BlockingCollection" objects cannot be copied or assigned 564 | BlockingCollection(const BlockingCollection&) = delete; 565 | BlockingCollection& operator=(const BlockingCollection&) = delete; 566 | 567 | ~BlockingCollection() { 568 | } 569 | 570 | /// Gets the bounded capacity of this BlockingCollection instance. 571 | /// @return The bounded capacity of the collection. 572 | size_t bounded_capacity() { 573 | std::lock_guard guard(lock_); 574 | return bounded_capacity_; 575 | } 576 | 577 | /// Gets the current state of this BlockingCollection instance. 578 | /// @return The current state of the collection. 579 | /// @see BlockingCollectionState 580 | BlockingCollectionState state() { 581 | std::lock_guard guard(lock_); 582 | return state_; 583 | } 584 | 585 | /// Gets whether this BlockingCollection instance is full. 586 | /// @return True if the collection is full; otherwise false. 587 | bool is_full() { 588 | std::lock_guard guard(lock_); 589 | return is_full_i(); 590 | } 591 | 592 | /// Gets whether this BlockingCollection instance is empty. 593 | /// @return True if the collection is empty; otherwise false. 594 | bool is_empty() { 595 | std::lock_guard guard(lock_); 596 | return is_empty_i(); 597 | } 598 | 599 | /// Gets the number of items contained in the BlockingCollection 600 | /// instance. 601 | /// If any method in BlockingCollection is executing while the size 602 | /// property is being accessd, the return value 603 | /// is approximate. size may reflect a number that is either greater 604 | /// than or less than the actual number of 605 | /// items in the BlockingCollection. 606 | /// @return The number of item in the collection. 607 | size_t size() { 608 | std::lock_guard guard(lock_); 609 | return container_.size(); 610 | } 611 | 612 | /// Gets whether this BlockingCollection instance has been 613 | /// deactivated. 614 | /// @return True is this collection has been deactivated. 615 | /// Otherwise false. 616 | bool is_deactivated() { 617 | std::lock_guard guard(lock_); 618 | return state_ == BlockingCollectionState::Deactivated; 619 | } 620 | 621 | /// Gets whether this BlockingCollection instance has been marked 622 | /// as complete for adding and is empty. 623 | /// @return True if this collection has been marked as complete for 624 | /// adding and is empty. Otherwise false. 625 | bool is_completed() { 626 | std::lock_guard guard(lock_); 627 | return is_completed_i(); 628 | } 629 | 630 | /// Gets whether this BlockingCollection instance has been marked 631 | /// as complete for adding. 632 | /// @return True if this collection has been marked as complete for 633 | /// adding. Otherwise false. 634 | bool is_adding_completed() { 635 | std::lock_guard guard(lock_); 636 | return is_adding_completed_i(); 637 | } 638 | 639 | /// Pulses this BlockingCollection instance to wake up any waiting 640 | /// threads. 641 | /// Changes the collection's state to Pulsed. Future Add and Take 642 | /// operations proceed 643 | /// as in the Activated state. 644 | /// @return The BlockingCollection's state before this call. 645 | /// @see BlockingCollectionState 646 | BlockingCollectionState pulse() { 647 | std::lock_guard guard(lock_); 648 | return deactivate_i(true); 649 | } 650 | 651 | /// Deactivate this BlockingCollection instance and wakeup all 652 | /// threads waiting 653 | /// on the collection so they can continue. No items are removed from 654 | /// the collection, 655 | /// however. Any other operations called until the collection is 656 | /// activated again will immediately return 657 | /// BlockingCollectionStatus::NotActivated. 658 | /// @return The BlockingCollection's state before this call. 659 | /// @see BlockingCollectionState 660 | /// @see BlockingCollectionStatus 661 | BlockingCollectionState deactivate() { 662 | std::lock_guard guard(lock_); 663 | return deactivate_i(false); 664 | } 665 | 666 | /// Reactivate this BlockingCollection instance so that threads 667 | /// can Add and Take 668 | /// items again. 669 | /// @return The BlockingCollection's state before this call. 670 | /// @see BlockingCollectionState 671 | BlockingCollectionState activate() { 672 | std::lock_guard guard(lock_); 673 | return activate_i(); 674 | } 675 | 676 | /// Releases all items from this BlockingCollection instance 677 | /// but does not mark it deactivated. 678 | /// @return The number of items flushed. 679 | size_t flush() { 680 | std::lock_guard guard(lock_); 681 | 682 | auto itemsFlushed = container_.size(); 683 | 684 | T item; 685 | 686 | while (container_.size() > 0) { 687 | container_.try_take(item); 688 | } 689 | 690 | not_empty_condition_var_.size(0); 691 | not_full_condition_var_.size(0); 692 | 693 | return itemsFlushed; 694 | } 695 | 696 | /// Marks the BlockingCollection instances as not accepting any more 697 | /// additions. 698 | /// After a collection has been marked as complete for adding, adding 699 | /// to the collection 700 | /// is not permitted and attempts to remove from the collection will 701 | /// not wait when the collection is empty. 702 | void complete_adding() { 703 | std::lock_guard guard(lock_); 704 | 705 | if (is_adding_completed_) 706 | return; 707 | 708 | is_adding_completed_ = true; 709 | 710 | not_empty_condition_var_.broadcast(); 711 | not_full_condition_var_.broadcast(); 712 | } 713 | 714 | /// Gets the number of consumer threads that are actively taking items 715 | /// from this BlockingCollection instance. 716 | /// @return The number of active consumer threads. 717 | /// @see AttachConsumer 718 | size_t active_consumers() { 719 | std::lock_guard guard(lock_); 720 | return not_empty_condition_var_.active(); 721 | } 722 | 723 | /// Gets the number of producer threads that are actively adding items 724 | /// to this BlockingCollection instance. 725 | /// @return The number of active producer threads. 726 | /// @see AttachProducer 727 | size_t active_producers() { 728 | std::lock_guard guard(lock_); 729 | return not_full_condition_var_.active(); 730 | } 731 | 732 | /// Gets the total number of consumer threads that can take items 733 | /// from this BlockingCollection instance. 734 | /// @return The total number of consumer threads. 735 | /// @see AttachConsumer 736 | size_t total_consumers() { 737 | std::lock_guard guard(lock_); 738 | return not_empty_condition_var_.total(); 739 | } 740 | 741 | /// Gets the total number of producer threads that can add items 742 | /// to this BlockingCollection instance. 743 | /// @return The total number of producer threads. 744 | /// @see AttachProducer 745 | size_t total_producers() { 746 | std::lock_guard guard(lock_); 747 | return not_full_condition_var_.total(); 748 | } 749 | 750 | /// Registers a consumer thread with this BlockingCollection 751 | /// instance. 752 | /// @see TotalConsumers 753 | void attach_consumer() { 754 | std::lock_guard guard(lock_); 755 | not_empty_condition_var_.attach(); 756 | } 757 | 758 | /// Unregisters a consumer thread with this BlockingCollection 759 | /// instance. 760 | /// @see TotalConsumers 761 | void detach_consumer() { 762 | std::lock_guard guard(lock_); 763 | not_empty_condition_var_.detach(); 764 | } 765 | 766 | /// Registers a producer thread with this BlockingCollection 767 | /// instance. 768 | /// @see TotalProducers 769 | void attach_producer() { 770 | std::lock_guard guard(lock_); 771 | not_full_condition_var_.attach(); 772 | } 773 | 774 | /// Unregisters a producer thread with this BlockingCollection 775 | /// instance. 776 | /// @see TotalProducers 777 | void detach_producer() { 778 | std::lock_guard guard(lock_); 779 | not_full_condition_var_.detach(); 780 | } 781 | 782 | /// Adds the given element value to the BlockingCollection. 783 | /// The new element is initialized as a copy of value. 784 | /// If a bounded capacity was specified when this instance of 785 | /// BlockingCollection was initialized, 786 | /// a call to Add may block until space is available to store the 787 | /// provided item. 788 | /// @param value the value of the element to add 789 | /// @return A BlockCollectionStatus code. 790 | /// @see BlockingCollectionStatus 791 | BlockingCollectionStatus add(const T& value) { 792 | return try_emplace_timed(std::chrono::milliseconds(-1), value); 793 | } 794 | 795 | /// Adds the given element value to the BlockingCollection. 796 | /// Value is moved into the new element. 797 | /// If a bounded capacity was specified when this instance of 798 | /// BlockingCollection was initialized, 799 | /// a call to Add may block until space is available to store the 800 | /// provided item. 801 | /// @param value the value of the element to add 802 | /// @return A BlockCollectionStatus code. 803 | /// @see BlockingCollectionStatus 804 | BlockingCollectionStatus add(T&& value) { 805 | return try_emplace_timed(std::chrono::milliseconds(-1), 806 | std::forward(value)); 807 | } 808 | 809 | /// Tries to add the given element value to the BlockingCollection. 810 | /// The new element is initialized as a copy of value. 811 | /// If the collection is a bounded collection, and is full, this method 812 | /// immediately returns without adding the item. 813 | /// @param value the value of the element to try to add 814 | /// @return A BlockCollectionStatus code. 815 | /// @see BlockingCollectionStatus 816 | BlockingCollectionStatus try_add(const T& value) { 817 | return try_emplace_timed(std::chrono::milliseconds::zero(), value); 818 | } 819 | 820 | /// Tries to add the given element value to the BlockingCollection. 821 | /// Value is moved into the new element. 822 | /// If the collection is a bounded collection, and is full, this 823 | /// method immediately returns without adding the item. 824 | /// @param value the value of the element to try to add 825 | BlockingCollectionStatus try_add(T&& value) { 826 | return try_emplace_timed(std::chrono::milliseconds::zero(), 827 | std::forward(value)); 828 | } 829 | 830 | /// Tries to add the given element value to the BlockingCollection 831 | /// within the specified time period. 832 | /// Value is moved into the new element. 833 | /// @param value the value of the element to try to add 834 | /// @param rel_time An object of type std::chrono::duration 835 | /// representing the maximum time to spend waiting. 836 | /// @return A BlockCollectionStatus code. 837 | /// @see BlockingCollectionStatus 838 | /// @see http://en.cppreference.com/w/cpp/chrono/duration 839 | template 840 | BlockingCollectionStatus try_add_timed(U&& value, 841 | const std::chrono::duration& rel_time) { 842 | return try_emplace_timed(rel_time, std::forward(value)); 843 | } 844 | 845 | /// Adds new element to the BlockingCollection. 846 | /// The arguments args... are forwarded to the constructor as 847 | /// std::forward(args)....If a bounded capacity was specified 848 | /// when this instance of BlockingCollection was initialized, 849 | /// a call to Emplace may block until space is available to store the 850 | /// provided item. 851 | /// @param args arguments to forward to the constructor of the element 852 | /// @return A BlockCollectionStatus code. 853 | /// @see BlockingCollectionStatus 854 | template 855 | BlockingCollectionStatus emplace(Args&&... args) { 856 | return try_emplace_timed(std::chrono::milliseconds(-1), 857 | std::forward(args)...); 858 | } 859 | 860 | /// Tries to add new element to the BlockingCollection. 861 | /// The arguments args... are forwarded to the constructor as 862 | /// std::forward(args).... 863 | /// If the collection is a bounded collection, and is full, this method 864 | /// immediately 865 | /// returns without adding the item. 866 | /// @param args arguments to forward to the constructor of the element 867 | /// @return A BlockCollectionStatus code. 868 | /// @see BlockingCollectionStatus 869 | template 870 | BlockingCollectionStatus try_emplace(Args&&... args) { 871 | return try_emplace_timed(std::chrono::milliseconds::zero(), 872 | std::forward(args)...); 873 | } 874 | 875 | /// Tries to add the given element value to the BlockingCollection 876 | /// within the specified time period. 877 | /// The arguments args... are forwarded to the constructor as 878 | /// std::forward(args).... 879 | /// If the collection is a bounded collection, and is full, this 880 | /// method immediately returns without adding the item. 881 | /// @param args arguments to forward to the constructor of the element 882 | /// @param rel_time An object of type std::chrono::duration 883 | /// representing the maximum time to spend waiting. 884 | /// @return A BlockCollectionStatus code. 885 | /// @see BlockingCollectionStatus 886 | /// @see http://en.cppreference.com/w/cpp/chrono/duration 887 | template 888 | BlockingCollectionStatus try_emplace_timed( 889 | const std::chrono::duration& rel_time, 890 | Args&&... args) { 891 | { 892 | std::unique_lock guard(lock_); 893 | 894 | auto status = wait_not_full_condition(guard, rel_time); 895 | 896 | if (BlockingCollectionStatus::Ok != status) 897 | return status; 898 | 899 | if (!container_.try_emplace(std::forward(args)...)) 900 | return BlockingCollectionStatus::InternalError; 901 | 902 | signal(container_.size(), false); 903 | } 904 | return BlockingCollectionStatus::Ok; 905 | } 906 | 907 | /// Removes an item from the BlockingCollection. 908 | /// A call to Take may block until an item is available to be removed. 909 | /// @param[out] item The item removed from the collection. 910 | /// @return A BlockCollectionStatus code. 911 | /// @see BlockingCollectionStatus 912 | BlockingCollectionStatus take(T& item) { 913 | return try_take(item, std::chrono::milliseconds(-1)); 914 | } 915 | 916 | /// Tries to remove an item from the BlockingCollection. 917 | /// If the collection is empty, this method immediately returns without 918 | /// taking an item. 919 | /// @param[out] item The item removed from the collection. 920 | /// @return A BlockCollectionStatus code. 921 | /// @see BlockingCollectionStatus 922 | BlockingCollectionStatus try_take(T& item) { 923 | return try_take(item, std::chrono::milliseconds::zero()); 924 | } 925 | 926 | /// Tries to remove an item from the BlockingCollection in the 927 | /// specified time period. 928 | /// @param[out] item The item removed from the collection. 929 | /// @param rel_time An object of type std::chrono::duration 930 | /// representing the maximum time to spend waiting. 931 | /// @return A BlockCollectionStatus code. 932 | /// @see BlockingCollectionStatus 933 | /// @see http://en.cppreference.com/w/cpp/chrono/duration 934 | template BlockingCollectionStatus 935 | try_take(T& item, const std::chrono::duration& rel_time) { 936 | { 937 | std::unique_lock guard(lock_); 938 | 939 | auto status = wait_not_empty_condition(guard, rel_time); 940 | 941 | if (BlockingCollectionStatus::Ok != status) 942 | return status; 943 | 944 | if (!container_.try_take(item)) 945 | return BlockingCollectionStatus::InternalError; 946 | 947 | signal(container_.size(), true); 948 | } 949 | return BlockingCollectionStatus::Ok; 950 | } 951 | 952 | /// Adds the items from range [first, last] to the 953 | /// BlockingCollection. 954 | /// If a bounded capacity was specified when this instance of 955 | /// BlockingCollection was initialized, 956 | /// a call to Add may block until space is available to store the 957 | /// provided items. 958 | /// Use std::make_move_iterator if the elements should be moved 959 | /// instead of copied. 960 | /// @param first The start range of elements to insert. 961 | /// @param last The end range of elements to insert. 962 | /// @param [out] added The actual number of elements added. 963 | /// @return A BlockCollectionStatus code. 964 | /// @see BlockingCollectionStatus 965 | template BlockingCollectionStatus 966 | add_bulk(Iterator first, Iterator last, size_t& added) { 967 | return try_add_bulk(first, last, added, 968 | std::chrono::milliseconds(-1)); 969 | } 970 | 971 | /// Tries to add the items from range [first, last] to the 972 | /// BlockingCollection. 973 | /// If the collection is a bounded collection, and is full, this method 974 | /// immediately returns without adding the items. 975 | /// Use std::make_move_iterator if the elements should be moved 976 | /// instead of copied. 977 | /// @param first The start range of elements to insert. 978 | /// @param last The end range of elements to insert. 979 | /// @param [out] added The actual number of elements added. 980 | /// @return A BlockCollectionStatus code. 981 | /// @see BlockingCollectionStatus 982 | template BlockingCollectionStatus 983 | try_add_bulk(Iterator first, Iterator last, size_t& added) { 984 | return try_add_bulk(first, last, added, 985 | std::chrono::milliseconds::zero()); 986 | } 987 | 988 | /// Tries to add the specified items from the range [first, last] to 989 | /// the BlockingCollection within 990 | /// the specified time period. 991 | /// Use std::make_move_iterator if the elements should be moved 992 | /// instead of copied. 993 | /// @param first The start range of elements to insert. 994 | /// @param last The end range of elements to insert. 995 | /// @param [out] added The actual number of elements added. 996 | /// @param rel_time An object of type std::chrono::duration representing 997 | /// the maximum time to spend waiting. 998 | /// @return A BlockCollectionStatus code. 999 | /// @see BlockingCollectionStatus 1000 | /// @see http://en.cppreference.com/w/cpp/chrono/durations 1001 | template 1002 | BlockingCollectionStatus try_add_bulk(Iterator first, Iterator last, 1003 | size_t& added, const std::chrono::duration& rel_time) { 1004 | { 1005 | added = 0; 1006 | 1007 | std::unique_lock guard(lock_); 1008 | 1009 | auto status = wait_not_full_condition(guard, rel_time); 1010 | 1011 | if (BlockingCollectionStatus::Ok != status) 1012 | return status; 1013 | 1014 | if (first == last) 1015 | return BlockingCollectionStatus::InvalidIterators; 1016 | 1017 | for (; first != last; ++first) { 1018 | if (!container_.try_add((*first))) 1019 | break; 1020 | ++added; 1021 | } 1022 | 1023 | signal(container_.size(), false); 1024 | } 1025 | return BlockingCollectionStatus::Ok; 1026 | } 1027 | 1028 | /// Takes up to count elements from the BlockingCollection. 1029 | /// A call to take_bulk may block until an element is available to be 1030 | /// removed. 1031 | /// Use std::make_move_iterator if the elements should be moved instead 1032 | /// of copied. 1033 | /// @param[out] first Contains first item taken. 1034 | /// @param count The number of elements to take from collection. 1035 | /// @param[out] taken The actual number of elements taken. 1036 | /// @return A BlockCollectionStatus code. 1037 | /// @see BlockingCollectionStatus 1038 | template BlockingCollectionStatus 1039 | take_bulk(Iterator first, size_t count, size_t& taken) { 1040 | return try_take_bulk(first, count, taken, 1041 | std::chrono::milliseconds(-1)); 1042 | } 1043 | 1044 | /// Takes up to count elements from the BlockingCollection. 1045 | /// If the collection is empty, this method immediately returns without 1046 | /// taking any items. 1047 | /// Use std::make_move_iterator if the elements should be moved instead 1048 | /// of copied. 1049 | /// @param[out] first Contains first item taken. 1050 | /// @param count The number of elements to take from collection. 1051 | /// @param[out] taken The actual number of elements taken. 1052 | /// @return A BlockCollectionStatus code. 1053 | /// @see BlockingCollectionStatus 1054 | template BlockingCollectionStatus 1055 | try_take_bulk(Iterator first, size_t count, size_t& taken) { 1056 | return try_take_bulk(first, count, taken, 1057 | std::chrono::milliseconds::zero()); 1058 | } 1059 | 1060 | /// Tries to take up to count elements from the BlockingCollection 1061 | /// within the specified time period. 1062 | /// If the collection is empty, this method immediately returns without 1063 | /// taking any items. 1064 | /// Use std::make_move_iterator if the elements should be moved instead 1065 | /// of copied. 1066 | /// @param[out] first Contains first item taken. 1067 | /// @param count The number of elements to take from collection. 1068 | /// @param[out] taken The actual number of elements taken. 1069 | /// @return A BlockCollectionStatus code. 1070 | /// @see BlockingCollectionStatus 1071 | /// @see http://en.cppreference.com/w/cpp/chrono/durations 1072 | template 1073 | BlockingCollectionStatus try_take_bulk(Iterator first, size_t count, 1074 | size_t& taken, const std::chrono::duration& rel_time) { 1075 | { 1076 | taken = 0; 1077 | 1078 | if (count == 0) 1079 | return BlockingCollectionStatus::Ok; 1080 | 1081 | std::unique_lock guard(lock_); 1082 | 1083 | auto status = wait_not_empty_condition(guard, rel_time); 1084 | 1085 | if (BlockingCollectionStatus::Ok != status) 1086 | return status; 1087 | 1088 | auto end = first + count; 1089 | 1090 | for (; first != end; ++first) { 1091 | if (!container_.try_take((*first))) 1092 | break; 1093 | 1094 | if (++taken == count) 1095 | break; 1096 | } 1097 | 1098 | signal(container_.size(), true); 1099 | } 1100 | return BlockingCollectionStatus::Ok; 1101 | } 1102 | 1103 | private: 1104 | class Iterator { 1105 | public: 1106 | Iterator(BlockingCollection &collection) 1108 | : collection_(collection), status_(BlockingCollectionStatus::Ok), 1109 | wait_for_first_item(true) { 1110 | } 1111 | 1112 | Iterator(BlockingCollection &collection, 1114 | BlockingCollectionStatus status) 1115 | : collection_(collection), status_(status), wait_for_first_item(false) { 1116 | } 1117 | 1118 | // "Iterator" objects cannot be copied or assigned 1119 | Iterator(const BlockingCollection&) = delete; 1120 | Iterator& operator=(const Iterator&) = delete; 1121 | 1122 | bool operator!=(const Iterator& it) { 1123 | if (wait_for_first_item) { 1124 | wait_for_first_item = false; 1125 | status_ = collection_.try_take(item_, 1126 | // -1 forces TryTake to wait 1127 | std::chrono::milliseconds(-1)); 1128 | } 1129 | 1130 | return !(status_ != BlockingCollectionStatus::Ok); 1131 | } 1132 | 1133 | Iterator& operator++() { 1134 | status_ = collection_.try_take(item_, 1135 | std::chrono::milliseconds(-1)); 1136 | return *this; 1137 | } 1138 | 1139 | T& operator*() { 1140 | return item_; 1141 | } 1142 | 1143 | private: 1144 | BlockingCollection 1145 | &collection_; 1146 | BlockingCollectionStatus status_; 1147 | bool wait_for_first_item; 1148 | T item_; 1149 | }; 1150 | 1151 | public: 1152 | Iterator begin() { return { *this }; } 1153 | Iterator end() { return { *this }; } 1154 | 1155 | private: 1156 | // the member functions below assume lock is held! 1157 | 1158 | /// The implementation for the Deactivate method. 1159 | /// This method is not thread safe. 1160 | /// @see Deactivate 1161 | BlockingCollectionState deactivate_i(bool pulse) { 1162 | auto previous_state = state_; 1163 | 1164 | if (previous_state != BlockingCollectionState::Deactivated) { 1165 | if (pulse) 1166 | state_ = BlockingCollectionState::Pulsed; 1167 | else 1168 | state_ = BlockingCollectionState::Deactivated; 1169 | 1170 | not_empty_condition_var_.broadcast(); 1171 | not_full_condition_var_.broadcast(); 1172 | } 1173 | 1174 | return previous_state; 1175 | } 1176 | 1177 | /// The implementation for the Activate method. 1178 | /// This method is not thread safe. 1179 | /// @see Activate 1180 | BlockingCollectionState activate_i() { 1181 | auto previous_state = state_; 1182 | 1183 | state_ = BlockingCollectionState::Activated; 1184 | 1185 | return previous_state; 1186 | } 1187 | 1188 | /// The implementation for the is_full method. 1189 | /// This method is not thread safe. 1190 | /// @see is_full 1191 | bool is_full_i() { 1192 | return bounded_capacity_ != SIZE_MAX && 1193 | container_.size() >= bounded_capacity_; 1194 | } 1195 | 1196 | /// The implementation for the is_empty method. 1197 | /// This method is not thread safe. 1198 | /// @see is_empty 1199 | bool is_empty_i() { 1200 | return container_.size() == 0; 1201 | } 1202 | 1203 | /// The implementation for the is_completed method. 1204 | /// This method is not thread safe. 1205 | /// @see is_completed 1206 | bool is_completed_i() { 1207 | return is_adding_completed_ && is_empty_i(); 1208 | } 1209 | 1210 | /// The implementation for the is_adding_completed method. 1211 | /// This method is not thread safe. 1212 | /// @see is_adding_completed 1213 | bool is_adding_completed_i() { 1214 | return is_adding_completed_; 1215 | } 1216 | 1217 | protected: 1218 | /// Wraps the condition variable signal methods. 1219 | /// This method updates the size property on both 1220 | /// condition variables before invoking the signal 1221 | /// method on the specified condition variable. 1222 | void signal(size_t itemCount, bool signal_not_full) { 1223 | not_empty_condition_var_.size(itemCount); 1224 | not_full_condition_var_.size(itemCount); 1225 | 1226 | if (signal_not_full) { 1227 | // signal only if capacity is bounded 1228 | if (bounded_capacity_ != SIZE_MAX) { 1229 | not_full_condition_var_.signal(); 1230 | } 1231 | } else { 1232 | not_empty_condition_var_.signal(); 1233 | } 1234 | } 1235 | 1236 | /// The method waits on the "not full" condition variable whenever 1237 | /// the collection becomes full. 1238 | /// It atomically releases lock, blocks the current executing thread, 1239 | /// and adds it to the 1240 | /// list of threads waiting on the "not full" condition variable. The 1241 | /// thread will be unblocked 1242 | /// when notify_all() or notify_one() is executed, or when the relative 1243 | /// timeout rel_time expires. 1244 | /// It may also be unblocked spuriously. When unblocked, regardless of 1245 | /// the reason, lock is reacquired 1246 | /// and wait_not_full_condition() exits. 1247 | /// @param lock An object of type std::unique_lock which must be locked 1248 | /// by the current thread. 1249 | /// @param rel_time An object of type std::chrono::duration representing 1250 | /// the maximum time to spend waiting. 1251 | /// @return A BlockCollectionStatus code. 1252 | /// @see BlockingCollectionStatus 1253 | /// @see http://en.cppreference.com/w/cpp/chrono/duration 1254 | template BlockingCollectionStatus 1255 | wait_not_full_condition(std::unique_lock& lock, 1256 | const std::chrono::duration& rel_time) { 1257 | if (state_ == BlockingCollectionState::Deactivated) 1258 | return BlockingCollectionStatus::NotActivated; 1259 | 1260 | if (is_adding_completed_i()) 1261 | return BlockingCollectionStatus::AddingCompleted; 1262 | 1263 | auto status = BlockingCollectionStatus::Ok; 1264 | 1265 | while (is_full_i()) { 1266 | if (rel_time == std::chrono::duration::zero()) { 1267 | status = BlockingCollectionStatus::TimedOut; 1268 | break; 1269 | } 1270 | 1271 | if (is_adding_completed_i()) { 1272 | status = BlockingCollectionStatus::AddingCompleted; 1273 | break; 1274 | } 1275 | 1276 | if (rel_time.count() < 0) { 1277 | not_full_condition_var_.wait(lock); 1278 | } else { 1279 | if (not_full_condition_var_.wait_for(lock, rel_time)) { 1280 | status = BlockingCollectionStatus::TimedOut; 1281 | break; 1282 | } 1283 | } 1284 | 1285 | // Add/TryAdd methods and CompleteAdding should not 1286 | // be called concurrently - invalid operation 1287 | 1288 | if (is_adding_completed_i()) { 1289 | status = BlockingCollectionStatus::CompleteAddingConcurrent; 1290 | break; 1291 | } 1292 | 1293 | if (state_ != BlockingCollectionState::Activated) { 1294 | status = BlockingCollectionStatus::NotActivated; 1295 | break; 1296 | } 1297 | } 1298 | return status; 1299 | } 1300 | 1301 | /// The method waits on the "not empty" condition variable whenever the 1302 | /// collection becomes empty. 1303 | /// It atomically releases lock, blocks the current executing thread, 1304 | /// and adds it to the 1305 | /// list of threads waiting on the "not empty" condition variable. The 1306 | /// thread will be unblocked 1307 | /// when notify_all() or notify_one() is executed, or when the relative 1308 | /// timeout rel_time expires. 1309 | /// It may also be unblocked spuriously. When unblocked, regardless of 1310 | /// the reason, lock is reacquired 1311 | /// and wait_not_empty_condition() exits. 1312 | /// @param lock An object of type std::unique_lock which must be locked 1313 | /// by the current thread. 1314 | /// @param rel_time An object of type std::chrono::duration representing 1315 | /// the maximum time to spend waiting. 1316 | /// @return A BlockCollectionStatus code. 1317 | /// @see BlockingCollectionStatus 1318 | /// @see http://en.cppreference.com/w/cpp/chrono/duration 1319 | template BlockingCollectionStatus 1320 | wait_not_empty_condition(std::unique_lock& lock, 1321 | const std::chrono::duration& rel_time) { 1322 | if (state_ == BlockingCollectionState::Deactivated) 1323 | return BlockingCollectionStatus::NotActivated; 1324 | 1325 | if (is_completed_i()) 1326 | return BlockingCollectionStatus::Completed; 1327 | 1328 | auto status = BlockingCollectionStatus::Ok; 1329 | 1330 | while (is_empty_i()) { 1331 | if (rel_time == std::chrono::duration::zero()) { 1332 | status = BlockingCollectionStatus::TimedOut; 1333 | break; 1334 | } 1335 | 1336 | if (is_adding_completed_i()) { 1337 | status = BlockingCollectionStatus::AddingCompleted; 1338 | break; 1339 | } 1340 | 1341 | if (rel_time.count() < 0) { 1342 | not_empty_condition_var_.wait(lock); 1343 | } else { 1344 | if (not_empty_condition_var_.wait_for(lock, rel_time)) { 1345 | status = BlockingCollectionStatus::TimedOut; 1346 | break; 1347 | } 1348 | } 1349 | 1350 | if (state_ != BlockingCollectionState::Activated) { 1351 | status = BlockingCollectionStatus::NotActivated; 1352 | break; 1353 | } 1354 | } 1355 | 1356 | return status; 1357 | } 1358 | 1359 | ContainerType& container() { 1360 | return container_; 1361 | } 1362 | 1363 | LockType& lock() { 1364 | return lock_; 1365 | } 1366 | 1367 | private: 1368 | BlockingCollectionState state_; 1369 | 1370 | size_t bounded_capacity_; 1371 | bool is_adding_completed_; 1372 | 1373 | typename ConditionVariableGenerator::NotEmptyType not_empty_condition_var_; 1374 | typename ConditionVariableGenerator::NotFullType not_full_condition_var_; 1375 | 1376 | // Synchronizes access to the BlockCollection. 1377 | LockType lock_; 1378 | // The underlying Container (e.g. Queue, Stack). 1379 | ContainerType container_; 1380 | }; 1381 | 1382 | /// @class PriorityContainer 1383 | /// Represents a priority based collection. Items with the highest priority 1384 | /// will be at the head of the collection. 1385 | /// Implements the implicitly defined IProducerConsumerCollection policy. 1386 | /// @tparam T The type of items in the collection. 1387 | /// @tparam ComparerType The type of comparer to use when comparing items. 1388 | template 1389 | class PriorityContainer { 1390 | public: 1391 | using container_type = std::deque; 1392 | using size_type = typename container_type::size_type; 1393 | using value_type = typename container_type::value_type; 1394 | using value_comparer = ComparerType; 1395 | 1396 | /// Initializes a new instance of the PriorityContainer class. 1397 | PriorityContainer() 1398 | : bounded_capacity_(SIZE_MAX) { 1399 | } 1400 | 1401 | /// Sets the max number of elements this container can hold. 1402 | /// @param bounded_capacity The max number of elements this 1403 | /// container can hold. 1404 | void bounded_capacity(size_t bounded_capacity) { 1405 | bounded_capacity_ = bounded_capacity; 1406 | } 1407 | 1408 | /// Gets the max number of elements this container can hold. 1409 | /// @returns The max number of elements this container can hold. 1410 | size_t bounded_capacity() { 1411 | return bounded_capacity_; 1412 | } 1413 | 1414 | /// Gets the number of elements contained in the collection. 1415 | /// @returns The number of elements contained in the collection. 1416 | size_type size() { 1417 | return container_.size(); 1418 | } 1419 | 1420 | /// Attempts to add an object to the collection according to the item's 1421 | /// priority. 1422 | /// @param new_item The object to add to the collection. 1423 | /// @returns True if the object was added successfully; otherwise, 1424 | /// false. 1425 | bool try_add(const value_type& new_item) { 1426 | if (container_.size() == bounded_capacity_) 1427 | return false; 1428 | return try_emplace(new_item); 1429 | } 1430 | 1431 | /// Attempts to add an object to the collection according to the item's 1432 | /// priority. 1433 | /// @param new_item The object to add to the collection. 1434 | /// @returns True if the object was added successfully; otherwise, 1435 | /// false. 1436 | bool try_add(value_type&& new_item) { 1437 | if (container_.size() == bounded_capacity_) 1438 | return false; 1439 | return try_emplace(std::forward(new_item)); 1440 | } 1441 | 1442 | /// Attempts to add an element to the collection according to the 1443 | /// element's priority. 1444 | /// This new element is constructed in place using args as the 1445 | /// arguments for its construction. 1446 | /// @param args Arguments forwarded to construct the new element. 1447 | template bool try_emplace(Args&&... args) { 1448 | if (container_.size() == bounded_capacity_) 1449 | return false; 1450 | if (container_.empty()) { 1451 | container_.emplace_front(std::forward(args)...); 1452 | } else { 1453 | T new_item(args...); 1454 | 1455 | // search from back to front (i.e. from the lowest priority to 1456 | // the highest priority) for 1457 | // item with a priority greater than or equal to new_item's 1458 | // priority 1459 | 1460 | typename container_type::reverse_iterator itr = std::find_if( 1461 | container_.rbegin(), container_.rend(), 1462 | [&new_item, this](value_type &item) { 1463 | return this->comparer_(item, new_item) >= 0; 1464 | }); 1465 | 1466 | if (itr == container_.rend()) { 1467 | // if at end then new_item's priority is now the highest 1468 | container_.emplace_front(std::move(new_item)); 1469 | } else if (itr == container_.rbegin()) { 1470 | // if at start then new_item's priority is now the lowest 1471 | container_.emplace_back(std::move(new_item)); 1472 | } else { 1473 | // insert the new item behind the item of greater or 1474 | // equal priority. This ensures that FIFO order is 1475 | // maintained when items of the same priority are 1476 | // inserted consecutively. 1477 | container_.emplace(itr.base(), std::move(new_item)); 1478 | } 1479 | } 1480 | return true; 1481 | } 1482 | 1483 | /// Attempts to remove and return the highest priority object from the 1484 | /// collection. 1485 | /// @param [out] item When this method returns, if the object was 1486 | /// removed and returned successfully, item contains 1487 | /// the removed object. If no object was available to be removed, the 1488 | /// value is unspecified. 1489 | /// @returns True if an object was removed and returned successfully; 1490 | /// otherwise, false. 1491 | bool try_take(value_type& item) { 1492 | if (container_.empty()) 1493 | return false; 1494 | item = container_.front(); 1495 | container_.pop_front(); 1496 | return true; 1497 | } 1498 | 1499 | /// Attempts to remove and return the lowest priority object from the 1500 | /// collection. 1501 | /// @param [out] item When this method returns, if the object was 1502 | /// removed and returned successfully, item contains 1503 | /// the removed object. If no object was available to be removed, the 1504 | /// value is unspecified. 1505 | /// @returns True if an object was removed and returned successfully; 1506 | /// otherwise, false. 1507 | bool try_take_prio(value_type& item) { 1508 | if (container_.empty()) 1509 | return false; 1510 | 1511 | bool init_current_priority = true; 1512 | value_type* current_priority; 1513 | 1514 | typename container_type::reverse_iterator itr = std::find_if_not( 1515 | container_.rbegin(), container_.rend(), 1516 | [¤t_priority, &init_current_priority, this](value_type &item) -> bool { 1517 | // Find the first version of the earliest item (i.e., 1518 | // preserve FIFO order for items at the same priority). 1519 | 1520 | if (init_current_priority) { 1521 | current_priority = &item; 1522 | init_current_priority = false; 1523 | return true; 1524 | } 1525 | bool continue_search = this->comparer_(item, *current_priority) <= 0; 1526 | if (continue_search) { 1527 | current_priority = &item; 1528 | } 1529 | return continue_search; 1530 | }); 1531 | 1532 | if (itr == container_.rend()) { 1533 | item = container_.front(); 1534 | container_.pop_front(); 1535 | } else { 1536 | typename container_type::iterator base = itr.base(); 1537 | item = (*base); 1538 | container_.erase(base); 1539 | } 1540 | 1541 | return true; 1542 | } 1543 | 1544 | private: 1545 | size_t bounded_capacity_; 1546 | container_type container_; 1547 | value_comparer comparer_; 1548 | }; 1549 | 1550 | /// @class PriorityComparer 1551 | /// This is the default PriorityContainer comparer. 1552 | /// It expects that the objects being compared have overloaded 1553 | /// < and > operators. 1554 | /// @tparam T The type of objects to compare. 1555 | template class PriorityComparer { 1556 | public: 1557 | /// Initializes a new instance of the PriorityComparer class. 1558 | PriorityComparer() { 1559 | } 1560 | /// Compares two objects and returns a value indicating whether one is 1561 | /// less than, equal to, or greater than the other. 1562 | /// Implement this method to provide a customized sort order comparison 1563 | /// for type T. 1564 | /// @param x The first object to compare. 1565 | /// @param y The second object to compare. 1566 | /// @return A signed integer that indicates the relative values of 1567 | /// x and y, as shown in the following table. 1568 | /// 1569 | /// Value | Meaning 1570 | /// ------------------|--------------------- 1571 | /// Less than zero | x is less than y. 1572 | /// Zero | x equals y. 1573 | /// Greater than zero | x is greater than y. 1574 | /// 1575 | int operator() (const T& x, const T& y) const { 1576 | if (x < y) 1577 | return -1; 1578 | else if (x > y) 1579 | return 1; 1580 | else 1581 | return 0; 1582 | } 1583 | }; 1584 | 1585 | template>, 1587 | typename ConditionVariableGenerator = StdConditionVariableGenerator> 1588 | class PriorityBlockingCollection : public BlockingCollection { 1589 | public: 1590 | using base = BlockingCollection; 1591 | 1592 | /// Initializes a new instance of the PriorityBlockingCollection 1593 | /// class without an upper-bound. 1594 | PriorityBlockingCollection() 1595 | : base() { 1596 | } 1597 | 1598 | /// Initializes a new instance of the PriorityBlockingCollection 1599 | /// class with the specified upper-bound. 1600 | /// @param capacity The bounded size of the collection. 1601 | explicit PriorityBlockingCollection(size_t capacity) 1602 | : base(capacity) { 1603 | } 1604 | 1605 | // "PriorityBlockingCollection" objects cannot be copied or assigned 1606 | PriorityBlockingCollection(const PriorityBlockingCollection&) = delete; 1607 | PriorityBlockingCollection& operator=(const PriorityBlockingCollection&) = delete; 1608 | 1609 | /// Removes the lowest priority item from the 1610 | /// PriorityBlockingCollection. 1611 | /// A call to TakePrio may block until an item is available to be 1612 | /// removed. 1613 | /// @param[out] item The lowest priority item removed from the 1614 | /// collection. 1615 | void take_prio(T& item) { 1616 | try_take_prio(item, std::chrono::milliseconds(-1)); 1617 | } 1618 | 1619 | /// Tries to remove the lowest priority item from the 1620 | /// PriorityBlockingCollection. 1621 | /// If the collection is empty, this method immediately returns 1622 | /// immediately without taking an item. 1623 | /// @param[out] item The lowest priority item removed from the 1624 | /// collection. 1625 | /// @return A BlockCollectionStatus code. 1626 | /// @see BlockingCollectionStatus 1627 | BlockingCollectionStatus try_take_prio(T& item) { 1628 | return try_take_prio(item, std::chrono::milliseconds::zero()); 1629 | } 1630 | 1631 | /// Tries to remove the lowest priority item from the 1632 | /// PriorityBlockingCollection in the specified time period. 1633 | /// @param[out] item The lowest priority item removed from the 1634 | /// collection. 1635 | /// @param rel_time An object of type std::chrono::duration 1636 | /// representing the maximum time to spend waiting. 1637 | /// @return A BlockCollectionStatus code. 1638 | /// @see BlockingCollectionStatus 1639 | /// @see http://en.cppreference.com/w/cpp/chrono/duration 1640 | template BlockingCollectionStatus 1641 | try_take_prio(T& item, 1642 | const std::chrono::duration& rel_time) { 1643 | { 1644 | std::unique_lock 1645 | guard(base::lock()); 1646 | 1647 | auto status = base::wait_not_empty_condition(guard, rel_time); 1648 | 1649 | if (BlockingCollectionStatus::Ok != status) 1650 | return status; 1651 | 1652 | if (!base::container().try_take_prio(item)) 1653 | return BlockingCollectionStatus::InternalError; 1654 | 1655 | base::signal(base::container().size(), true); 1656 | } 1657 | return BlockingCollectionStatus::Ok; 1658 | } 1659 | 1660 | /// Takes up to count low priority elements from the 1661 | /// PriorityBlockingCollection. 1662 | /// A call to take_prio_bulk may block until an element is available 1663 | /// to be removed. 1664 | /// Use std::make_move_iterator if the elements should be moved instead 1665 | /// of copied. 1666 | /// @param[out] first Contains first item taken. 1667 | /// @param count The number of elements to take from collection. 1668 | /// @param[out] taken The actual number of elements taken. 1669 | /// @return A BlockCollectionStatus code. 1670 | /// @see BlockingCollectionStatus 1671 | template BlockingCollectionStatus 1672 | take_prio_bulk(Iterator first, size_t count, size_t& taken) { 1673 | return try_take_prio_bulk(first, count, taken, 1674 | std::chrono::milliseconds(-1)); 1675 | } 1676 | 1677 | /// Takes up to count low priority elements from the 1678 | /// PriorityBlockingCollection. 1679 | /// If the collection is empty, this method immediately returns without 1680 | /// taking any items. 1681 | /// Use std::make_move_iterator if the elements should be moved instead 1682 | /// of copied. 1683 | /// @param[out] first Contains first item taken. 1684 | /// @param count The number of elements to take from collection. 1685 | /// @param[out] taken The actual number of elements taken. 1686 | /// @return A BlockCollectionStatus code. 1687 | /// @see BlockingCollectionStatus 1688 | template BlockingCollectionStatus 1689 | try_take_prio_bulk(Iterator first, size_t count, size_t& taken) { 1690 | return try_take_prio_bulk(first, count, taken, 1691 | std::chrono::milliseconds::zero()); 1692 | } 1693 | 1694 | /// Tries to take up to count low priority elements from the 1695 | /// PriorityBlockingCollection within 1696 | /// the specified time period. 1697 | /// If the collection is empty, this method immediately returns without 1698 | /// taking any items. 1699 | /// Use std::make_move_iterator if the elements should be moved instead 1700 | /// of copied. 1701 | /// @param[out] first Contains first item taken. 1702 | /// @param count The number of elements to take from collection. 1703 | /// @param[out] taken The actual number of elements taken. 1704 | /// @return A BlockCollectionStatus code. 1705 | /// @see BlockingCollectionStatus 1706 | /// @see http://en.cppreference.com/w/cpp/chrono/durations 1707 | template 1708 | BlockingCollectionStatus try_take_prio_bulk(Iterator first, 1709 | size_t count, size_t& taken, 1710 | const std::chrono::duration& rel_time) { 1711 | { 1712 | taken = 0; 1713 | 1714 | if (count == 0) 1715 | return BlockingCollectionStatus::Ok; 1716 | 1717 | std::unique_lock 1718 | guard(base::lock()); 1719 | 1720 | auto status = base::wait_not_empty_condition(guard, rel_time); 1721 | 1722 | if (BlockingCollectionStatus::Ok != status) 1723 | return status; 1724 | 1725 | auto end = first + count; 1726 | 1727 | for (; first != end; ++first) { 1728 | if (!base::container().try_take_prio((*first))) 1729 | break; 1730 | 1731 | if (++taken == count) 1732 | break; 1733 | } 1734 | } 1735 | return BlockingCollectionStatus::Ok; 1736 | } 1737 | }; 1738 | 1739 | namespace detail { 1740 | struct ProducerType {}; 1741 | struct ConsumerType {}; 1742 | 1743 | template< typename T > 1744 | struct is_producer : std::false_type { }; 1745 | 1746 | template<> 1747 | struct is_producer : std::true_type { }; 1748 | 1749 | /// @class Guard 1750 | /// Implements a strictly scope-based BlockingCollection wrapper. 1751 | /// The class Guard is a BlockingCollection wrapper that provides a 1752 | /// convenient RAII-style 1753 | /// mechanism for attaching the current thread as a producer or 1754 | /// consumer to the BlockingCollection for the 1755 | /// duration of the scoped block. 1756 | /// 1757 | /// When a Guard object is created, it attaches the current thread as a 1758 | /// producer or consumer of the 1759 | /// BlockingCollection it is given. When control leaves the scope in 1760 | /// which the Guard object 1761 | /// was created, the Guard is destructed and the current thread is 1762 | /// detached from the BlockingCollection. 1763 | /// 1764 | /// The Guard class makes it simple for threads to register as producer 1765 | /// or consumers with the BlockingCollection 1766 | /// instance. Plus it ensures the thread will be detached from the 1767 | /// BlockingCollection in an 1768 | /// exception scenario. 1769 | /// 1770 | /// The Guard class is non-copyable. 1771 | /// @tparam BlockingCollectionType The type of BlockingCollection to 1772 | /// Guard. 1773 | /// @tparam GuardType The type of Guard to create (i.e. ProducerType 1774 | /// or ConsumerType). 1775 | /// @see ProducerGuard 1776 | /// @see ConsumerGuard 1777 | /// http://en.wikipedia.com/wiki/Resource_Acquisition_Is_Initialization 1778 | template 1779 | class Guard { 1780 | public: 1781 | explicit Guard(BlockingCollectionType &collection) 1782 | : collection_(collection) { 1783 | attach_i(is_producer()); 1784 | } 1785 | 1786 | Guard(Guard const&) = delete; 1787 | Guard& operator=(Guard const&) = delete; 1788 | 1789 | ~Guard() { 1790 | detach_i(is_producer()); 1791 | } 1792 | 1793 | private: 1794 | void attach_i(std::false_type) { 1795 | collection_.attach_consumer(); 1796 | } 1797 | 1798 | void attach_i(std::true_type) { 1799 | collection_.attach_producer(); 1800 | } 1801 | 1802 | void detach_i(std::false_type) { 1803 | collection_.detach_consumer(); 1804 | } 1805 | 1806 | void detach_i(std::true_type) { 1807 | collection_.detach_producer(); 1808 | } 1809 | 1810 | BlockingCollectionType& collection_; 1811 | }; 1812 | } // namespace detail 1813 | 1814 | /// A type alias for Guard 1815 | template 1816 | using ProducerGuard = detail::Guard; 1817 | 1818 | /// A type alias for Guard 1819 | template 1820 | using ConsumerGuard = detail::Guard; 1821 | 1822 | /// A type alias for BlockingCollection - a last in-first out 1823 | /// (LIFO) BlockingCollection. 1824 | template 1825 | using BlockingStack = BlockingCollection>; 1826 | 1827 | /// A type alias for BlockingCollection - a first in-first out 1828 | /// (FIFO) BlockingCollection. 1829 | template 1830 | using BlockingQueue = BlockingCollection>; 1831 | 1832 | /// A type alias for BlockingCollection - a priority-based 1833 | /// BlockingCollection. 1834 | template 1835 | using BlockingPriorityQueue = BlockingCollection>>; 1837 | 1838 | #ifdef _WIN32 1839 | /// @class WIN32_CRITICAL_SECTION 1840 | /// WIN32_CRITICAL_SECTION wraps the Win32 CRITICAL_SECTION object so that 1841 | /// it meets the BasicLockable requirement (i.e. lock and unlock member 1842 | /// functions). 1843 | /// 1844 | /// @see WIN32_SRWLOCK 1845 | class WIN32_CRITICAL_SECTION { 1846 | public: 1847 | WIN32_CRITICAL_SECTION() { 1848 | InitializeCriticalSection(&cs_); 1849 | } 1850 | 1851 | void lock() { 1852 | EnterCriticalSection(&cs_); 1853 | } 1854 | 1855 | void unlock() { 1856 | LeaveCriticalSection(&cs_); 1857 | } 1858 | 1859 | CRITICAL_SECTION& native_handle() { 1860 | return cs_; 1861 | } 1862 | private: 1863 | CRITICAL_SECTION cs_; 1864 | }; 1865 | 1866 | /// @class WIN32_SRWLOCK 1867 | /// WIN32_SRWLOCK wraps the Win32 SRWLOCK object so that it meets the 1868 | /// BasicLockable requirement (i.e. lock and unlock member functions). 1869 | /// 1870 | /// @see WIN32_CRITICAL_SECTION 1871 | class WIN32_SRWLOCK { 1872 | public: 1873 | WIN32_SRWLOCK() { 1874 | InitializeSRWLock(&srw_); 1875 | } 1876 | 1877 | void lock() { 1878 | AcquireSRWLockExclusive(&srw_); 1879 | } 1880 | 1881 | void unlock() { 1882 | ReleaseSRWLockExclusive(&srw_); 1883 | } 1884 | 1885 | SRWLOCK& native_handle() { 1886 | return srw_; 1887 | } 1888 | private: 1889 | SRWLOCK srw_; 1890 | }; 1891 | 1892 | template <> 1893 | struct ConditionVarTraits { 1894 | static void initialize(CONDITION_VARIABLE& cond_var) { 1895 | InitializeConditionVariable(&cond_var); 1896 | } 1897 | 1898 | static void signal(CONDITION_VARIABLE& cond_var) { 1899 | WakeConditionVariable(&cond_var); 1900 | } 1901 | 1902 | static void broadcast(CONDITION_VARIABLE& cond_var) { 1903 | WakeAllConditionVariable(&cond_var); 1904 | } 1905 | 1906 | static void wait(CONDITION_VARIABLE& cond_var, 1907 | std::unique_lock& lock) { 1908 | SleepConditionVariableSRW(&cond_var, &lock.mutex()->native_handle(), 1909 | INFINITE, 0); 1910 | } 1911 | 1912 | template static bool wait_for( 1913 | CONDITION_VARIABLE& cond_var, std::unique_lock& lock, 1914 | const std::chrono::duration& rel_time) { 1915 | DWORD milliseconds = static_cast(rel_time.count()); 1916 | 1917 | if (!SleepConditionVariableSRW(&cond_var, 1918 | &lock.mutex()->native_handle(), milliseconds, 0)) { 1919 | if (GetLastError() == ERROR_TIMEOUT) 1920 | return true; 1921 | } 1922 | 1923 | return false; 1924 | } 1925 | }; 1926 | 1927 | template <> 1928 | struct ConditionVarTraits { 1929 | static void initialize(CONDITION_VARIABLE& cond_var) { 1930 | InitializeConditionVariable(&cond_var); 1931 | } 1932 | 1933 | static void signal(CONDITION_VARIABLE& cond_var) { 1934 | WakeConditionVariable(&cond_var); 1935 | } 1936 | 1937 | static void broadcast(CONDITION_VARIABLE& cond_var) { 1938 | WakeAllConditionVariable(&cond_var); 1939 | } 1940 | 1941 | static void wait(CONDITION_VARIABLE& cond_var, 1942 | std::unique_lock& lock) { 1943 | SleepConditionVariableCS(&cond_var, &lock.mutex()->native_handle(), 1944 | INFINITE); 1945 | } 1946 | 1947 | template static bool wait_for( 1948 | CONDITION_VARIABLE& cond_var, 1949 | std::unique_lock& lock, 1950 | const std::chrono::duration& rel_time) { 1951 | DWORD milliseconds = static_cast(rel_time.count()); 1952 | 1953 | if (!SleepConditionVariableCS(&cond_var, 1954 | &lock.mutex()->native_handle(), milliseconds)) { 1955 | if (GetLastError() == ERROR_TIMEOUT) 1956 | return true; 1957 | } 1958 | 1959 | return false; 1960 | } 1961 | }; 1962 | 1963 | using Win32ConditionVariableGenerator = ConditionVariableGenerator< 1964 | ThreadContainer, NotFullSignalStrategy<16>, 1965 | NotEmptySignalStrategy<16>, CONDITION_VARIABLE, WIN32_SRWLOCK>; 1966 | #endif 1967 | } // namespace code_machina 1968 | 1969 | #endif /* BlockingCollection_h */ 1970 | --------------------------------------------------------------------------------