Created
April 25, 2014 10:53
-
-
Save joshpeterson/11285436 to your computer and use it in GitHub Desktop.
An example of a simple queue class with internal locking for a blog post.
This file contains 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
#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