线程未被销毁
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
,但还有很多)。
去掉所有那些"(type)foo"强制转换,它们迫使编译器接受实际上不适合的东西。你将不得不通过用正确的类型替换东西来修复一些错误。对于传递给线程的上下文指针,从demo*
到void*
的转换是隐式的。扭转这种局面的正确演员阵容是static_cast<demo*>(data)
。若需要,也可以对隐式转换使用静态强制转换。函数中也缺少返回值,唯一允许的情况是在main()中。我提到这一点的原因是,从形式上讲,任何事情都可能发生在你的程序中,因为这些事情会导致未定义的行为。
然后,您输出的是"inst的值",但实际上输出的是名为"inst"的局部变量的地址,这是不同的。这可能只是增加了你的困惑。
现在,针对您的问题,CloseHandle()不会停止线程。它只会释放你的手柄。您想要的是WaitForSingleObject()或其兄弟之一。
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- CoInitialize()在单独的线程上崩溃而不返回
- c++中的线程池
- 线程之间的布尔停止信号
- 为什么std::async使用同一个线程运行函数
- 用于矢量处理的多个线程
- C++为线程工作动态地分割例程
- 为什么我不能在 while 循环中创建线程?