Last active
December 11, 2020 04:49
-
-
Save ProjectInitiative/0573b78f3fb74fa4c10f036b64fb55e0 to your computer and use it in GitHub Desktop.
A very useful C++ thread safe queue found here: https://stackoverflow.com/a/16075550
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef SAFE_QUEUE | |
#define SAFE_QUEUE | |
#include <queue> | |
#include <mutex> | |
#include <condition_variable> | |
// A threadsafe-queue. | |
template <class T> | |
class SafeQueue | |
{ | |
public: | |
SafeQueue(void) | |
: q() | |
, m() | |
, c() | |
{} | |
~SafeQueue(void) | |
{} | |
// Add an element to the queue. | |
void enqueue(T t) | |
{ | |
std::lock_guard<std::mutex> lock(m); | |
q.push(t); | |
c.notify_one(); | |
} | |
// Get the "front"-element. | |
// If the queue is empty, wait till a element is available. | |
T dequeue(void) | |
{ | |
std::unique_lock<std::mutex> lock(m); | |
while(q.empty()) | |
{ | |
// release lock as long as the wait and reacquire it afterwards. | |
c.wait(lock); | |
} | |
T val = q.front(); | |
q.pop(); | |
return val; | |
} | |
size_type size() | |
{ | |
std::lock_guard<std::mutex> lock(m); | |
return q.size(); | |
} | |
bool empty() | |
{ | |
std::lock_quard<std::mutex> lock(m); | |
return q.empty(); | |
} | |
void clear() | |
{ | |
std::lock_guard<std::mutex> lock(m); | |
std::queue<T> empty; | |
std::swap(q, empty); | |
} | |
private: | |
std::queue<T> q; | |
mutable std::mutex m; | |
std::condition_variable c; | |
}; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment