Note that there are some explanatory texts on larger screens.

plurals
  1. POboost thread deadlock, can anyone check why?
    primarykey
    data
    text
    <p>I tried to write a program that can have mutiple-threaded reads and writes. It works fine with one read and one write, but it ended in deadlock when I use two reads and one write.</p> <p>Can anyone help to check?</p> <pre><code>const int BUF_SIZE = 10; const int ITERS = 100; boost::mutex io_mutex; class buffer { public: typedef boost::mutex::scoped_lock scoped_lock; buffer() : p(0), c(0), full(0) {} void put(int m) { scoped_lock lock(mutex); if (full == BUF_SIZE) { { boost::mutex::scoped_lock lock(io_mutex); std::cout &lt;&lt; "Buffer is full. Waiting..." &lt;&lt; std::endl; } while (full == BUF_SIZE) cond.wait(lock); } buf[p] = m; p = (p+1) % BUF_SIZE; ++full; cond.notify_all(); } int get() { scoped_lock lk(mutex); if (full == 0) { { boost::mutex::scoped_lock lock(io_mutex); std::cout &lt;&lt; "Buffer is empty. Waiting..." &lt;&lt; std::endl; } while (full == 0) cond.wait(lk); } int i = buf[c]; c = (c+1) % BUF_SIZE; --full; cond.notify_one(); return i; } private: boost::mutex mutex; boost::condition cond; unsigned int p, c, full; int buf[BUF_SIZE]; }; buffer buf; void writer() { for (int n = 0; n &lt; ITERS; ++n) { { boost::mutex::scoped_lock lock(io_mutex); std::cout &lt;&lt; "sending: " &lt;&lt; n &lt;&lt; std::endl; } buf.put(n); } } void reader() { for (int x = 0; x &lt; ITERS; ++x) { int n = buf.get(); { boost::mutex::scoped_lock lock(io_mutex); std::cout &lt;&lt; "reader1: received: " &lt;&lt; n &lt;&lt; std::endl; } } } int main(int argc, char* argv[]) { boost::thread thrd1(&amp;reader); boost::thread thrd2(&amp;writer); boost::thread thrd3(&amp;reader); std::string str; thrd1.join(); thrd2.join(); thrd3.join(); std::getline(std::cin,str); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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