Skip to content

Instantly share code, notes, and snippets.

@cydu
Last active December 14, 2015 06:49
Show Gist options
  • Save cydu/5045568 to your computer and use it in GitHub Desktop.
Save cydu/5045568 to your computer and use it in GitHub Desktop.
thread-safe blocking queue
class ThreadQueue {
private:
ThreadQueue& operator=(ThreadQueue&);
list<int> data;
pthread_mutex lock;
pthread_mutex empty_lock;
public:
ThreadQueue() {
pthread_mutex_init(&lock,NULL);
thread_mutex_init(&empty_lock,NULL);
}
int push(int d) {
pthread_mutex_lock(&lock);
data.push_back(d);
pthread_mutex_unlock(&lock);
// unlock has no side effect when it's not locked
pthread_mutex_unlock(&empty_lock);
return 0;
}
int pop() {
while(1) {
pthread_mutex_lock(&empty_lock);
pthread_mutex_lock(&lock);
if(!data.empty()) {
// ok, get two lock, and data is not empty, break while loop to do real pop
break;
}
//cancel all lock, retry again!
pthread_mutex_unlock(&lock);
pthread_mutex_unlock(&empty_lock);
// sleep 0 second used to force this thread release the cpu
sleep(0);
}
int val = data.pop_front();
int is_empty = data.empty();
pthread_mutex_unlock(&lock);
if(!is_empty) {
pthread_mutex_unlock(&empty_lock);
}
return val;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment