为什么Main函数上的Sleep()停止所有线程?

为什么Sleep()停止所有创建的线程?我想创建一个线程,但是将Main函数保持睡眠状态,直到线程完成。

bool _finished = false;

void testcount(void *p){
 int i = 0;
 while(i<=30){
  i++;
  std::cout<<i<<"\n";
  Sleep(1000);
 }
_finished = true;
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved){
 HANDLE test = NULL;
 test = CreateThread(NULL,NULL,(LpthREAD_START_ROUTINE)testcount,NULL);
 if(test)
  std::cout<<"test thread created";
 CloseHandle(test);

 while(!_finished)
  Sleep(1000);

return true;
}

我现在正在这样尝试,但是程序从未完成,因为whileSleep一起停止了线程。线程未完成时,我不想在Main上返回任何内容。有解决办法吗?

bsyang1225 回答:为什么Main函数上的Sleep()停止所有线程?

  1. DllMain的调用由Win32进行序列化。

  2. 所有新线程均通过调用DllMain(带有线程附加标志)开始,并调用方法传递给CreateThread

因此,您的线程正在等待调用DllMain,直到您的第一个线程离开DllMain时才会发生。

评论员约翰·谢里丹(John Sheridan)指出Raymond Chen's blog post from 2007是一个很好的解释。

PS。为了正确进行C / C ++库初始化,您应该直接使用_beginthread or _beginthreadex而不是CreateThread

,

新线程被阻止,因为您的主线程没有离开DllMain,如Richard的回答所述。

您的代码也包含数据争用并且即使在修复此死锁之后也具有未定义的行为。新线程同时写入_finished,主线程从_finished读取。假定C ++ 11可用,您可以尝试使用std::atomic<bool>而不是bool来解决此问题,或者可以使用Win32原语进行线程同步。

使用std::atomic<bool>对标准解决方案进行的更改:

#include <atomic>

std::atomic<bool> finished_{false};

// Rest remains the same
本文链接:https://www.f2er.com/3138611.html

大家都在问