Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example of a simple queue class with internal locking for a blog post.
#include <deque>
#include <mutex>
#include <cassert>
template<typename T, typename MutexType = std::mutex>
class queue
{
public:
void enqueue(T value) {
std::lock_guard<MutexType> guard(mutex_);
q_.push_back(value);
}
private:
std::deque<T> q_;
MutexType mutex_;
};
class mock_mutex {
public:
void lock() {
lock_called_ = true;
}
void unlock() {}
bool was_locked() {
return lock_called_;
}
private:
static bool lock_called_;
};
bool mock_mutex::lock_called_ = false;
int main() {
mock_mutex mutex_tracker;
queue<int, mock_mutex> subject;
subject.enqueue(42);
assert(mutex_tracker.was_locked());
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment