Is deadlock possible in this simple scenario?
<p>Please see the following code:</p>

<pre><code>std::mutex mutex;
std::condition_variable cv;
std::atomic&lt;bool&gt; terminate;

// Worker thread routine
void work() {
    while( !terminate ) {
        {
            std::unique_lock&lt;std::mutex&gt; lg{ mutex };
            cv.wait(lg);

            // Do something
        }
        // Do something
    }
}

// This function is called from the main thread
void terminate_worker() {
    terminate = true;
    cv.notify_all();
    worker_thread.join();
}
</code></pre>

<p>Is the following scenario can happen?</p>

<ol>
<li>Worker thread is waiting for signals.</li>
<li>The main thread called <code>terminate_worker()</code>;

<ul>
<li>The main thread set the atomic variable <code>terminate</code> to <code>true</code>, and then signaled to the worker thread.</li>
<li>Worker thread now wakes up, do its job and load from <code>terminate</code>. At this step, <em>the change to</em> <code>terminate</code> <em>made by the main thread is not yet seen</em>, so the worker thread decides to wait for another signal.</li>
</ul></li>
<li>Now deadlock occurs...</li>
</ol>

<p>I wonder this is ever possible. As I understood, <code>std::atomic</code> only guarantees no race condition, but memory order is a different thing. Questions:</p>

<ol>
<li>Is this possible?</li>
<li>If this is not possible, is this possible if <code>terminate</code> is not an atomic variable but is simply <code>bool</code>? Or atomicity has nothing to do with this?</li>
<li>If this is possible, what should I do?</li>
</ol>

<p>Thank you.</p>