有没有可能设置这样一种属性 
可以在父线程结束时自动结束子线程 ?

解决方案 »

  1.   

    HANDLE hd = CreateThread(NULL,0,RecvProc,NULL,0,NULL);
    CloseHandle(hd);
    关闭句柄就行了,这样子当主线程结束时副线程就自动结束了。
      

  2.   

    首先感谢楼上的,但是假如我用
    PHANDLE phThread2;
    *phThread2=CreateThread (&sa,0,thread_fun2,(LPVOID)NULL,CREATE_SUSPENDED,&thread_id);
    CloseHandle (*phThread2);
    为什么不行呢?麻烦稍微指点一下
      

  3.   

    父线程结束前,发消息给子线程,子线程收到后调用AfxEndThread或者::PostQuitMessage退出。
      

  4.   

    或者我们可以在子线程中监视主线程,
    使用::GetExitCodeThread查看退出码是否为STILL_ACTIVE
    如果是,则主线程还在运行,若不是,则主线程已经退出,则自己也退出。
      

  5.   

    modaoshi3002你是说在父线程里D u p l i c a t e H a n d l e (GetCurrent.....)这样得到句柄然后再传给子线程?理论上可行,不过似乎有些低效.
      

  6.   

    不需要用 DuplicateHandle,因为如果线程存在,::GetExitCodeThread肯定是成功的,返回TRUE,退出码就是STILL_ACTIVE,如果线程不存在了,则GetExitCodeThread会失败,会返回FALSE的,这时就不需要看退出码是不是STILL_ACTIVE了。
    当然,这个只是我回答不了你的主线程被暴力退出的问题,才拿出的方法,不一定合适,因为这是主线程退出后,子线程才退出,和你本意就有差别了
    当然,如果你硬要使用,也可以的,也不一定需要 DuplicateHandle
    MSDN上,对于这个问题,还有一个推荐的方法:
    • Set the m_bAutoDelete data member to FALSE. This allows the CWinThread object to survive after the thread has been terminated. You can then access the m_hThread data member after the thread has been terminated. If you use this technique, however, you are responsible for destroying the CWinThread object as the framework will not automatically delete it for you. This is the preferred method.
     
    而DuplicateHandle是第二个方法,MSDN推荐第一个方法
      

  7.   

    不是啊,你要在子线程里调用GetExitCodeThread,不是一定要得到父线程的句柄吗?