我从列表
获得线程执行命令do
{
commandExec->criticalSection.EnterCS();
if (!commandExec->commands.empty())
{
commandExec->ExecuteCommand(commandExec->commands.front());
commandExec->commands.pop_front();
}
else
commandExec->criticalSection.SuspendThread();
commandExec->criticalSection.LeaveCS();
} while (commandExec->maintainCommandExecution);
和将命令添加到列表的第二个线程:
criticalSection.EnterCS();
commands.push_back(Command(code, parameters));
criticalSection.LeaveCS();
criticalSection.ResumeThread();
第一个线程在执行命令时可能会崩溃,因此第二个线程无法访问临界区:
如果线程在拥有临界区的所有权时终止,则临界区的状态是未定义的。 Source
那么,处理这个问题的好方法是什么? 我可以想到一些解决方案,但它们似乎很棘手(添加第三个线程,第二个关键部分等)
(criticalSection它只是CRITICAL_SECTION的简单包装器)
答案 0 :(得分:2)
您可以使用Mutex而不是关键部分(但要注意Understanding the consequences of WAIT_ABANDONED中列出的问题)。
答案 1 :(得分:2)
您可以创建一个LockCriticalSection类,它可以锁定构造函数中的关键部分并解析析构函数中的关键部分。
然后,在您的代码中,您将分配一个LockCriticalSection对象,以便您开始锁定。当对象LockCriticalSection超出范围时(因为函数正确终止或因异常而终止),临界区将自动释放。
以下是负责锁定和解锁关键部分的代码:
/// \brief This class locks a critical section in the
/// constructor and unlocks it in the destructor.
///
/// This helps to correctly release a critical section in
/// case of exceptions or premature exit from a function
/// that uses the critical section.
///
///////////////////////////////////////////////////////////
class LockCriticalSection
{
public:
/// \brief Creates the object LockCriticalSection and
/// lock the specified CRITICAL_SECTION.
///
/// @param pCriticalSection pointer to the CRITICAL_SECTION
/// to lock
///
///////////////////////////////////////////////////////////
LockCriticalSection(CRITICAL_SECTION* pCriticalSection):
m_pCriticalSection(pCriticalSection)
{
EnterCriticalSection(pCriticalSection);
}
/// \brief Destroy the object LockCriticalSection and
/// unlock the previously locked CRITICAL_SECTION.
///
///////////////////////////////////////////////////////////
virtual ~LockCriticalSection()
{
LeaveCriticalSection(m_pCriticalSection);
}
private:
CRITICAL_SECTION* m_pCriticalSection;
};
这是您问题中修改后的源代码:
do
{
{
LockCriticalSection lock(&criticalSectionToLock);
while (!commandExec->commands.empty())
{
commandExec->ExecuteCommand(commandExec->commands.front());
commandExec->commands.pop_front();
}
} // here the critical section is released
// suspend thread here
} while (commandExec->maintainCommandExecution);