我的应用程序在退出线程函数时崩溃了。这是我的线程的初始化方式:
LPTHREAD_START_ROUTINE pThreadStart = (LPTHREAD_START_ROUTINE)NotifyWindowThreadFn;
void * pvThreadData = reinterpret_cast<void *>(_pobjSerialPort);
// Create the exit notify window thread event handle.
_hNotifyWindowThreadExitEvent = ::CreateEvent(
NULL, // No security
TRUE, // Create a manual-reset event object
FALSE, // Initial state is non-signaled
NULL // No name specified
);
if ( _hNotifyWindowThreadExitEvent == NULL )
{
TRACE(_T("CreateNotifyWindow : Failed to get a handle for the exit message-only window event.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
return ::GetLastError();
}
// Create the notify window thread to begin execution on its own.
_hNotifyWindowThread = ::CreateThread(
NULL, // No security attributes.
0, // Use default initial stack size.
pThreadStart, // Function to execute in new thread.
pvThreadData, // Thread parameters.
0, // Use default creation settings.
NULL // Thread ID is not needed.
);
if ( _hNotifyWindowThread == NULL )
{
TRACE(_T("CreateNotifyWindow : Failed to create handle for message-only window thread.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
return ::GetLastError();
}
这是我的线程函数中被执行的部分:
DWORD NotifyWindowThreadFn( void * pParam )
{
static CNotifyWindow * pobjNotifyWindow = NULL;
CSerialPort * pobjSerialPort = reinterpret_cast<CSerialPort *>(pParam);
// Create notify window to handle surprize removal/insertion events...
try
{
pobjNotifyWindow = new CNotifyWindow();
}
catch ( DWORD error )
{
return error; // 1. PC gets here
}
catch ( long error )
{
return error;
}
catch ( ... )
{
return ERROR_CANNOT_MAKE;
}
/* Other stuff that is not executed due to return. */
} // 2. PC then gets here
当应用程序崩溃时,Visual Studio 给我这个错误信息:
Windows has triggered a breakpoint in CppTestConsole.exe.
This may be due to a corruption of the heap, which indicates a bug in CppTestConsole.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while CppTestConsole.exe has focus.
The output window may have more diagnostic information.
输出窗口没有任何特别有用的东西。只是……
The thread 'NotifyWindowThreadFn' (0x414) has exited with code 0 (0x0).
然后显示卸载了一堆DLL。当我单击 Break 按钮时,PC 位于 dbgheap.c 中 _CrtIsValidHeapPointer
的末尾。有没有人知道为什么我的应用程序在线程退出时崩溃?我不应该直接从线程函数中返回吗?谢谢。
最佳答案
我可能是错的,但您似乎正试图从工作线程创建窗口。不要这样做。 Windows 需要消息泵才能运行,而您的应用程序中只有一个消息泵——它在主线程中。
关于c++ - 应用程序在线程退出时崩溃 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4315719/