Do mutex locks happen in the same order they are asked?

喜夏-厌秋 提交于 2019-12-01 17:13:37

问题


I am currently trying to create a very simple thread pool using std::thread. In order to maintain threads 'alive' after their given task is done, I associate a std::mutex with each one of them.

The principle is somewhat like this:

// Thread loop
while (1)
{
  m_oMutex->lock();
  m_oMutex->unlock();
  m_bAvailable = false;
  m_oTask();
  m_bAvailable = true;
}

// ThreadPool function which gives a task to a thread
void  runTask(boost::function<void ()> oTask)
{
  [...]
  m_oThreads[i]->setTask(oTask);
  m_oMutexes[i]->unlock(); // same mutex as thread's m_oMutex
  m_oMutexes[i]->lock();
}

To find the i, the ThreadPool searches for a thread object with m_bAvailable set to true. It unlocks the corresponding mutex so the thread can lock it and execute its task. The thread unlocks it immediately so the ThreadPool can lock it again so the thread is halted once its task is done.

But the question is, will locks be made in the order the threads ask them? In other words, if a thread does a lock on a mutex, then the ThreadPool unlocks it and locks it again, am I sure that the lock will be given to the thread first? If not, is there a way to ensure it?


回答1:


No, you cannot guarantee that your thread loop will ever acquire the lock with your example as is. Use a conditional variable to signal to the thread loop that it should awake and take the lock. See std::condition_variable::wait(...). condition-variable

More on this topic in general can be found here http://en.wikipedia.org/wiki/Condition_variable. If you were using the pthread library, the equivalent call would be pthread_cond_wait in your "Thread loop" and pthread_cond_signal in your runTask function.



来源:https://stackoverflow.com/questions/9046746/do-mutex-locks-happen-in-the-same-order-they-are-asked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!