线程未被销毁

Thread is not getting Destroyed

本文关键字:线程      更新时间:2023-10-16

我正在一个多线程系统上工作,下面是我的代码类演示在.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。这些设置允许线程安全地使用使用静态存储的标准库函数(例如,strtokmktime,但还有很多)。

去掉所有那些"(type)foo"强制转换,它们迫使编译器接受实际上不适合的东西。你将不得不通过用正确的类型替换东西来修复一些错误。对于传递给线程的上下文指针,从demo*void*的转换是隐式的。扭转这种局面的正确演员阵容是static_cast<demo*>(data)。若需要,也可以对隐式转换使用静态强制转换。函数中也缺少返回值,唯一允许的情况是在main()中。我提到这一点的原因是,从形式上讲,任何事情都可能发生在你的程序中,因为这些事情会导致未定义的行为。

然后,您输出的是"inst的值",但实际上输出的是名为"inst"的局部变量的地址,这是不同的。这可能只是增加了你的困惑。

现在,针对您的问题,CloseHandle()不会停止线程。它只会释放你的手柄。您想要的是WaitForSingleObject()或其兄弟之一。