Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Usually you use a <em>producer-consumer-queue</em> for this type of work.</p> <p>Whenever the worker thread runs out of work he <code>wait()</code>s on a <code>boost::condition_variable</code> which is protected by the same <code>boost::mutex</code> as the stack holding the data for the worker thread (you might want to use a queue here instead to minimize the risk of unfair work scheduling).</p> <p>Your <code>PushFrame()</code> function now calls <code>notify_one()</code> on that condition variable whenever it inserts new data into the stack. That way, the worker thread will truly sleep (i.e. the OS scheduler will probably not give it any timeslice) until there is actually work to be done.</p> <p>The easiest thing to get wrong here is the locking of the mutex protecting both the stack and the condition_variable. Besides avoiding races on the data structures, you also need to take care that the condition_variable does not miss a notify call and therefore might get stuck waiting while there actually is more work available.</p> <pre><code>class Worker { void PushFrame(byte* data) { boost::lock_guard&lt;boost::mutex&gt; lk(m_mutex); // push the data // ... m_data_cond.notify_one(); } void DoWork() { while(!done) { boost::unique_lock&lt;boost::mutex&gt; lk(m_mutex); // we need a loop here as wait() may return spuriously while(is_out_of_work()) { // wait() will release the mutex and suspend the thread m_data_cond.wait(lk); // upon returning from wait() the mutex will be locked again } // do work from the queue // ... } } boost::mutex m_mutex; boost::condition_variable m_data_cond; [...] }; </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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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