![](/img/trans.png)
[英]QThread: Destroyed while thread is still running and QMutex destroyed
[英]Thread is not getting Destroyed
我正在研究多线程系统,我的代码类演示在.h文件中定义
当第二次执行主函数的循环时,下面的COMMENT1取前一个值
不关闭句柄关闭线程?
int threadentry(void* data)
{
demo* inst=(demo*) data;
cout << "Value of inst "<<hex << &inst<< endl;
string request;
cin>>request;
if(request==play)
{
inst->play;
cout << "Value of inst "<<hex << &inst<< endl;
// COMMENT1 here when the thread is executed second time from the main it is taking previous value
}
}
int main()
{
while(1)
{
demo* inst=new demo();
cout << "Value of inst "<<hex << &inst<< endl; //value is coming different from above
HANDLE threads;
DWORD threadId1;
if ((threads = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadentry,
(void *)inst, 0, &threadId1)) == NULL)
return -1;
//here is some Processing of data and after processing I close the handle
CloseHandle(threads);
delete inst;
system("pause");
}
}
否 - 关闭线程的句柄不会破坏线程本身。 线程应该在完成其工作时退出 (通过调用ExitThread
或仅通过从线程函数返回)。
在紧急情况下,你可以使用TerminateThread
杀死一个线程,但是应该为真正的紧急情况保留 - 它可以使进程处于不稳定状态,所以通常应该避免,如果你必须使用它,你可能想要尽快关闭这个过程。
另请注意,在使用标准库的程序中,直接使用CreateThread
并不安全 - 您应该调用_beginthread
或_beginthreadex
。 这些设置允许线程安全地使用使用静态存储的标准库函数(例如, strtok
和mktime
,但还有更多)。
删除所有那些“(类型)foo”强制转换,它们强制编译器接受实际上不适合的东西。 你必须通过用适当的类型替换东西来解决一些错误。 对于传递给线程的上下文指针,从demo*
到void*
的转换是隐式的。 正确的static_cast<demo*>(data)
是static_cast<demo*>(data)
。 如果需要,也可以使用静态强制转换进行隐式转换。 函数中也缺少返回值,唯一允许的情况是main()。 我提到的原因是,正式地说,任何事情都可能发生在您的程序中,因为这些事情会导致未定义的行为。
然后,您输出“inst of value”但实际输出称为“inst”的局部变量的地址,这是不同的。 这可能只会增加您的困惑。
现在,遇到问题,CloseHandle()不会停止线程。 它只释放你的手柄。 你想要的是WaitForSingleObject()或其中一个兄弟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.