【发布时间】:2021-05-10 18:12:38
【问题描述】:
标题几乎概括了我的问题。我有下面显示的这个功能,当我按下按钮加入线程时,应用程序停止响应。我对 C++ 中的多线程相当陌生,我真的不知道我在做什么或为什么会发生这种情况。
HWND hwnd;
//this stops the declaration of the thread from saying that hwnd doesn't exist
bool stopRaidAction;
void JoinLoop(HWND hwnd)
{
for (std::string tokenString; std::getline(std::cin,tFileContents,'\n');) {
if(stopRaidAction==false)
{
if(tokenString.length()==0){break;}
if(tokenString.length()!=0){
//send post request to join the server using token through proxy
}
}
if(stopRaidAction){break;}
}
}
std::thread joinThread(JoinLoop, hwnd);
问题在于“JOIN_RAID”
LRESULT CALLBACK WindowProcessMessages(HWND hwnd, UINT msg, WPARAM param, LPARAM lparam) {
switch (msg) {
case WM_CREATE:
Controls(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_COMMAND:
{
if ((HIWORD(param) == BN_CLICKED) && (lparam != 0))
{
switch (LOWORD(param))
{
case JOIN_RAID:
stopRaidAction=false;
MessageBeep(MB_OK);
joinThread.join();
break;
case STOP_RAID:
stopRaidAction=true;
MessageBeep(MB_OK);
break;
}
}
break;
}
default:
return DefWindowProc(hwnd, msg, param, lparam);
}
return 0;
}
【问题讨论】:
-
stopRaidAction不是atomic,所以你有一个数据竞争(一个线程读取和另一个没有同步的写入),这是未定义的行为。挂起是未定义行为的有效表现。 -
@Supergamer5465:看起来你加入线程的情况下,你永远不会触发线程函数中循环的终止条件。
-
我把它变成了原子的,但它仍然挂起。我怎么能触发这个“终止条件”?
标签: c++ multithreading winapi