I am trying to implement a thread-safe deque in C++.
ThreadSafeDeque
will be used by a FileLogger
class.
When threads call the log()
function of FileLogger
the messages will be push_back()
ed to ThreadSafeDeque
and return almost immediately. In a separate thread the FileLogger will pop_front()
messages and write them to a file in its own pace.
Am
Am I doing things correctly and efficient below?
#pragma once
#include <deque>
#include <mutex>
template<class T>
class ThreadSafeDeque {
public:
void pop_front_waiting(T &t) {
// unique_lock can be unlocked, lock_guard can not
std::unique_lock<std::mutex> lock{ mutex }; // locks
while(deque.empty()) {
condition.wait(lock); // unlocks, sleeps and relocks when woken up
}
t = deque.front();
deque.pop_front();
} // unlocks as goes out of scope
void push_back(const T &t) {
std::unique_lock<std::mutex> lock{ mutex };
deque.push_back(t);
lock.unlock();
condition.notify_one(); // wakes up pop_front_waiting
}
private:
std::deque<T> deque;
std::mutex mutex;
std::condition_variable condition;
};