C++11 thread hangs on locking mutex
<p>Using C++11 <code>std::thread</code>, <code>std::mutex</code>, I'm writing a simple worker thread.
However, I got a strange hang issue in locking <code>std::mutex</code>, which looks like both threads (main and worker thread) are trying to lock a mutex, but both are blocked.</p>

<p>Here's the full code</p>

<pre><code>#include &lt;thread&gt;
#include &lt;condition_variable&gt;
#include &lt;memory&gt;
#include &lt;iostream&gt;
#include &lt;list&gt;
std::condition_variable cv;
std::mutex m;
std::thread t;
bool shouldExit = false;
std::list&lt;int&gt; jobs;

void thread_func()
{
  std::unique_lock&lt;std::mutex&gt; lock(m);
  while (!shouldExit) {
    while (jobs.empty() &amp;&amp; !shouldExit) {
      cv.wait(lock);
    }
    // Do some stuff
    if (jobs.empty()) {
      continue;
    }
    // Get a job and do something with it
    if (!lock.owns_lock()) {
      lock.lock();  // &lt;&lt;&lt;&lt; Worker thread hang here
    }
    auto j = std::move(jobs.front());
    jobs.pop_front();
    lock.unlock();
    std::cout &lt;&lt; "Do something with job " &lt;&lt; j &lt;&lt; std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
  }
}

int main()
{
  t = std::thread(thread_func);

  for (int i = 1; i &lt; 100; ++i) {
    std::cout &lt;&lt; "Push to job " &lt;&lt; i &lt;&lt; std::endl;
    {
    std::lock_guard&lt;std::mutex&gt; lock(m); // &lt;&lt;&lt;&lt; main thread hang here
    jobs.push_back(i);
    cv.notify_one();
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
  }

  // To wait for thread exit
  shouldExit = true;
  cv.notify_one();
  t.join();
  return 0;
}
</code></pre>

<p>I'm compiling the code using below command on Ubuntu 14.04</p>

<pre><code>g++ -std=c++11 -g -O0 -pthread -o testthread testthread.cpp
</code></pre>

<p>The executing result is typically like this:</p>

<pre><code>$ ./testthread
Push to job 1
Do something with job 1
Push to job 2
Do something with job 2
Push to job 3
Push to job 4
</code></pre>

<p>The interesting part is, when I move one line code of sleeping-1ms in main thread into the <code>lock_guard</code> like below, the issue is gone.</p>

<pre><code>  for (int i = 1; i &lt; 100; ++i) {
    std::cout &lt;&lt; "Push to job " &lt;&lt; i &lt;&lt; std::endl;
    {
    std::lock_guard&lt;std::mutex&gt; lock(m);
    jobs.push_back(i);
    cv.notify_one();
    std::this_thread::sleep_for(std::chrono::milliseconds(1)); // Moved into lock_guard
    }
  }
</code></pre>

<p>I could not figure out why.
Could you help to explain the behavior of the code and what I did wrong?</p>

<p>[Update] I know re-writing the worker thread in certain way could fix the issue. But I still would like to know in the original code what exactly happens when the two threads are locking the mutex but both are blocked.</p>