Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>What you need is <em>reference stability</em>. I.e. you can use containers this way if the reference to the first element is not invalidated when the container is push_back'd. And even then, you'll want to obtain the reference to the front element under the lock.</p> <p>I'm more familiar with <code>std::condition_variable</code> for the event notification, so I'll use that:</p> <pre><code>#include &lt;mutex&gt; #include &lt;condition_variable&gt; #include &lt;deque&gt; std::mutex locker; std::deque&lt;int&gt; int_queue; std::condition_variable cv; void thread_1_2_3() { // use lock_guard instead of explicit lock/unlock // for exception safety std::lock_guard&lt;std::mutex&gt; lk(locker); int_queue_.push_back(1); cv.notify_one(); } void dispatch() { while (true) { bool some_condition = true; std::unique_lock&lt;std::mutex&gt; lk(locker); while (int_queue.empty()) cv.wait(lk); // get reference to front under lock int&amp; data = int_queue.front(); lk.unlock(); // now use the reference without worry while (some_condition) some_condition = some_operation(data); lk.lock(); int_queue.pop_front(); } } </code></pre> <p>23.3.3.4 [deque.modifiers] says this about <code>push_back</code>:</p> <blockquote> <p>An insertion at either end of the deque invalidates all the iterators to the deque, but has no effect on the validity of references to elements of the deque.</p> </blockquote> <p>That is the key to allowing you to hang onto that reference outside of the lock. If <code>thread_1_2_3</code> starts inserting or erasing in the middle, then you can no longer hang on to this reference.</p> <p>You can't use a <code>vector</code> this way. But you could use a <code>list</code> this way. Check each container you want to use this way for reference stability.</p>
    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.
    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