I have a problem with pthreads where I think I have a dead end. I created a blocking queue that I thought worked, but after doing a few more tests, I found that if I try to cancel several threads that block key_lock, I seem to be at a dead end.
The lock queue is very simple and looks like this:
template <class T> class Blocking_Queue { public: Blocking_Queue() { pthread_mutex_init(&_lock, NULL); pthread_cond_init(&_cond, NULL); } ~Blocking_Queue() { pthread_mutex_destroy(&_lock); pthread_cond_destroy(&_cond); } void put(T t) { pthread_mutex_lock(&_lock); _queue.push(t); pthread_cond_signal(&_cond); pthread_mutex_unlock(&_lock); } T pull() { pthread_mutex_lock(&_lock); while(_queue.empty()) { pthread_cond_wait(&_cond, &_lock); } T t = _queue.front(); _queue.pop(); pthread_mutex_unlock(&_lock); return t; } priavte: std::queue<T> _queue; pthread_cond_t _cond; pthread_mutex_t _lock; }
For testing, I created 4 threads that pull this blocking queue. I added several print statements to the lock queue, and each thread falls into the pthread_cond_wait () method. However, when I try to call pthread_cancel () and pthread_join () in each thread, the program just hangs.
I also tested this with only one thread, and it works great.
According to the documentation, pthread_cond_wait () is a cancellation point, so canceling a call in these threads should cause execution to stop (and this only works with one thread). However, pthread_mutex_lock is not a cancellation point. Can something happen in the same order when pthread_cancel () is called, the canceled thread passes the mutex before terminating and does not unlock it, and then when the next thread is canceled, it cannot use the mutex and deadlocks? Or is there something else I'm doing wrong.
Any advice would be great. Thanks:)
c ++ pthreads deadlock blockingqueue
vimalloc
source share