Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy this thread safe queue, creates a deadlock?
    primarykey
    data
    text
    <p>I've written my own version of thread safe queue. However, when I run this program, it hangs/deadlocks itself.</p> <p>Wondering, why is this locks/hangs forever.</p> <pre><code>void concurrentqueue::addtoQueue(const int number) { locker currentlock(lock_for_queue); numberlist.push(number); pthread_cond_signal(&amp;queue_availability_condition); } int concurrentqueue::getFromQueue() { int number = 0; locker currentlock(lock_for_queue); if ( empty() ) { pthread_cond_wait(&amp;queue_availability_condition,&amp;lock_for_queue); } number = numberlist.front(); numberlist.pop(); return number; } bool concurrentqueue::empty() { return numberlist.empty(); } </code></pre> <p>I've written, the class locker as RAII.</p> <pre><code>class locker { public: locker(pthread_mutex_t&amp; lockee): target(lockee) { pthread_mutex_lock(&amp;target); } ~locker() { pthread_mutex_unlock(&amp;target); } private: pthread_mutex_t target; }; </code></pre> <p>My writer/reader thread code is very simple. Writer thread, adds to the queue and reader thread, reads from the queue.</p> <pre><code>void * writeintoqueue(void* myqueue) { void *t = 0; concurrentqueue *localqueue = (concurrentqueue *) myqueue; for ( int i = 0; i &lt; 10 ; ++i) { localqueue-&gt;addtoQueue(i*10); } pthread_exit(t); } void * readfromqueue(void* myqueue) { void *t = 0; concurrentqueue *localqueue = (concurrentqueue *) myqueue; int number = 0; for ( int i = 0 ; i &lt; 10 ; ++i) { number = localqueue-&gt;getFromQueue(); std::cout &lt;&lt; "The number from the queue is " &lt;&lt; number &lt;&lt; std::endl; } pthread_exit(t); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload