C++多线程互斥锁"reset"

C++ multi-threading mutex lock "reset"

我在我的多线程应用程序中使用 std::mutex 来通过多个线程访问同一资源。这很好用。但是在我的代码的某些点,我必须使用 TerminateThread(...) 终止线程。当我再次开始线程时(使用 _beginthreadex),如果其中一个线程在终止时处于互斥锁,我会得到一个异常:

Concurrency::improper_lock bei Speicherort 0x03B4F3D0.

这是在 rtlocks.cpp 中抛出的,第 1184 行(在 bool critical_section::_Acquire_lock 中):

LockQueueNode * pPrevious = reinterpret_cast<LockQueueNode *>(InterlockedExchangePointer(&_M_pTail, pNewNode));

我想,如果我可以 "reset" 互斥锁,我会得到一个异常,对吧?我该怎么做?

(我用的是<process.h>

编辑

我尝试了以下方法:

std::mutex dataStorage_lock;
mutexHandler[0] = &dataStorage_lock; //storing all mutexs in an array

//when trying to delete:
delete mutexHandler[0];

但我得到:

Debug Assertion Failed!

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

您需要销毁互斥锁​​并创建一个全新的互斥锁,或者您可以修改代码,以便在等待互斥锁时可以中断(而不是终止)线程。有关中断的一些想法,请参见此处:http://www.boost.org/doc/libs/1_54_0/doc/html/thread/thread_management.html#thread.thread_management.tutorial.interruption

这是伪代码,但你应该明白了:

错误:

function thread_proc():
  for_ever:
    do_things

function stop_my_thread():
  TerminateThread(...)

对:

function thread_proc():
  while(not terminate_signal):
    do_things

function stop_my_thread():
  terminate_signal.set();  // signals the thread to terminate
  thread.join();           // waits for the thread to terminate