title: Do mutex locks happen in the same order they are asked?
body: <p>I am currently trying to create a very simple thread pool using <code>std::thread</code>.
  In order to maintain threads 'alive' after their given task is done, I associate a <code>std::mutex</code> with each one of them.</p>
  
  <p>The principle is somewhat like this:</p>
  
  <pre><code>// Thread loop
  while (1)
  {
    m_oMutex-&gt;lock();
    m_oMutex-&gt;unlock();
    m_bAvailable = false;
    m_oTask();
    m_bAvailable = true;
  }
  
  // ThreadPool function which gives a task to a thread
  void  runTask(boost::function&lt;void ()&gt; oTask)
  {
    [...]
    m_oThreads[i]-&gt;setTask(oTask);
    m_oMutexes[i]-&gt;unlock(); // same mutex as thread's m_oMutex
    m_oMutexes[i]-&gt;lock();
  }
  </code></pre>
  
  <p>To find the <code>i</code>, the <code>ThreadPool</code> searches for a thread object with <code>m_bAvailable</code> set to <code>true</code>. It unlocks the corresponding mutex so the <code>thread</code> can lock it and execute its task. The <code>thread</code> unlocks it immediately so the <code>ThreadPool</code> can lock it again so the <code>thread</code> is halted once its task is done.</p>
  
  <p>But the question is, will locks be made in the order the threads ask them? In other words, if a <code>thread</code> does a lock on a <code>mutex</code>, then the <code>ThreadPool</code> unlocks it and locks it again, am I sure that the lock will be given to the <code>thread</code> first? If not, is there a way to ensure it?</p>