Note that there are some explanatory texts on larger screens.

plurals
  1. POis this a correct use of boost condition variables?
    primarykey
    data
    text
    <p>I wrote the following program for alternatively incrementing and doubling a counter(increment first) using boost condition variables. Can any one tell me if this is the correct use of boost condition variables. It is working correctly. I don't understand the use of lock in wait function call. What does condition.wait(lock) mean? For example what is the use of two scoped locks in increment and multiply in this program. How can I avoid them?</p> <pre><code>#include &lt;boost/thread/thread.hpp&gt; #include &lt;boost/thread/mutex.hpp&gt; #include &lt;boost/bind.hpp&gt; #include &lt;boost/thread/locks.hpp&gt; #include &lt;boost/thread/condition_variable.hpp&gt; #include &lt;iostream&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; using namespace std; int counter=0; boost::mutex m1,m2; bool incremented=false,multiplied=false; boost::condition_variable c1,c2; void Increment() { { boost::mutex::scoped_lock lk(m1); counter++; incremented = true; c1.notify_one(); while(!multiplied) c2.wait(lk); multiplied=false; } } void Multiply() { { boost::mutex::scoped_lock lk(m2); while(!incremented) c1.wait(lk); incremented = false; counter = counter*2 ; multiplied = true; c2.notify_one(); } } void IncrementNtimes(int n){ for(int i=0;i&lt;n;i++){ Increment(); } } void MultiplyNtimes(int n){ for(int i=0;i&lt;n;i++){ Multiply(); } } int main(int argc, char* argv[]) { srand ( time(NULL) ); boost::thread thrd1(boost::bind(&amp;IncrementNtimes,20)); boost::thread thrd2(boost::bind(&amp;MultiplyNtimes,20)); thrd1.join(); thrd2.join(); cout&lt;&lt;"Main counter is:"&lt;&lt;counter&lt;&lt;endl; return 0; } </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.
    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