【问题标题】:On windows 7, thread appears to be hung at _endthreadex and Waitforsingleobject with a timeout doesn't signal在 Windows 7 上,线程似乎在 _endthreadex 处挂起,并且超时的 Waitforsingleobject 没有发出信号
【发布时间】:2020-11-23 05:44:26
【问题描述】:

我需要您的帮助来解决我们的桌面应用程序面临的随机挂起问题。

我们在单例类中实现了一个线程,以循环调用 Beep 和 Sleep API。所以我们启动线程来调用这些,然后在一段时间后,我们打破循环,在主线程中等待单个对象并退出线程。就在从线程函数返回之前,我们调用_endthreadex。这里有一个挂起。现在我不知道 _endthreadex 是否失败以及它如何在超时后停止 waitforsingleobject 发出信号。该代码的实现与 _beginthreadex 的示例非常相似。正如我所说,它非常随机地发生在少数机器上。

unsigned __stdcall SecondThreadFunc( void* pArguments )

{

printf( "In second thread...\n" );

while( m_iBeepMode == iBEEPON )

{

Beep(600, 100);

Sleep(100);

}

//I added a logging here, which gets logged in hang case.

_endthreadex( 0 );

return 0;

}

int main()

{

HANDLE hThread;

unsigned threadID;

printf( "Creating second thread...\n" );

// Create the second thread.

hThread = (HANDLE)_beginthreadex( NULL, 16384, &SecondThreadFunc, this, 0, &threadID );

// the below code is not exactly in the same method. We call it at a later time to stop the beep.

m_iBeepMode = BEEPOFF;

WaitForSingleObject( hThread, 10000 );

// Added a logging here, which doesn't get logged.

// Destroy the thread object.

CloseHandle( hThread );

}

【问题讨论】:

    标签: c++ multithreading windows-7


    【解决方案1】:

    您需要使您的 m_iBeepMode 原子化,以便在每次迭代时对其进行检查。就目前而言,由于编译器可以看到该函数中的任何内容都没有改变 m_iBeepMode,因此很可能会完全删除该条件。

    请注意,这曾经是 volatile 的领域,但 atomic 是更惯用的解决方案。

    【讨论】:

    • 感谢您的建议。这是否意味着它卡在了while循环中?我还在while循环中和循环之后添加了日志记录。我可以看到迭代正在发生,我们正确地退出了 while 循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    相关资源
    最近更新 更多