Last active
August 16, 2023 17:28
-
-
Save murphypei/d59cbcdf6c8485ed98510dc1f0b3ddca to your computer and use it in GitHub Desktop.
C++ thread safe queue
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 <condition_variable> | |
#include <mutex> | |
#include <queue> | |
// A threadsafe-queue. | |
template <class T> | |
class SafeQueue | |
{ | |
public: | |
SafeQueue() : q(), m(), c() {} | |
~SafeQueue() {} | |
// 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 avaiable. | |
T dequeue(void) | |
{ | |
std::unique_lock<std::mutex> lock(m); | |
while (q.empty()) | |
{ | |
// release lock as long as the wait and reaquire it afterwards. | |
c.wait(lock); | |
} | |
T val = q.front(); | |
q.pop(); | |
return val; | |
} | |
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