Last active
December 14, 2015 06:49
-
-
Save cydu/5045568 to your computer and use it in GitHub Desktop.
thread-safe blocking 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
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