如何在外部关闭执行中的线程并且释放资源?
是通过线程ID吗?
相关的API是什么?

解决方案 »

  1.   


    TerminateThread
    The TerminateThread function terminates a thread. BOOL TerminateThread(
      HANDLE hThread,    // handle to the thread
      DWORD dwExitCode   // exit code for the thread
    );
     
    Parameters
    hThread 
    Handle to the thread to terminate. 
    Windows NT: The handle must have THREAD_TERMINATE access. dwExitCode 
    Specifies the exit code for the thread. Use the GetExitCodeThread function to retrieve a thread's exit value. 
    Return Values
    If the function succeeds, the return value is nonzero.If the function fails, the return value is zero. To get extended error information, call GetLastError.
      

  2.   


    GetExitCodeThread
    The GetExitCodeThread function retrieves the termination status of the specified thread. BOOL GetExitCodeThread(
      HANDLE hThread,      // handle to the thread
      LPDWORD lpExitCode   // address to receive termination status
    );
     
    Parameters
    hThread 
    Handle to the thread. 
    Windows NT: The handle must have THREAD_QUERY_INFORMATION access. lpExitCode 
    Pointer to a 32-bit variable to receive the thread termination status. 
    Return Values
    If the function succeeds, the return value is nonzero.If the function fails, the return value is zero. To get extended error information, call GetLastError. ----------------------------------------------------------------------------------------------
    TerminateThread
    The TerminateThread function terminates a thread. BOOL TerminateThread(
      HANDLE hThread,    // handle to the thread
      DWORD dwExitCode   // exit code for the thread
    );
     
    Parameters
    hThread 
    Handle to the thread to terminate. 
    Windows NT: The handle must have THREAD_TERMINATE access. dwExitCode 
    Specifies the exit code for the thread. Use the GetExitCodeThread function to retrieve a thread's exit value. 
    Return Values
    If the function succeeds, the return value is nonzero.If the function fails, the return value is zero. To get extended error information, call GetLastError.-----------------------------------------------------------------------------------------------------------
    CloseHandle
    The CloseHandle function closes an open object handle. BOOL CloseHandle(
      HANDLE hObject   // handle to object to close
    );-----------------------------------------------------------------------------------------
    //首先调用GetExitCodeThread 获取ExitCode ,然后通过TerminateThread 来执行关闭线程的操作,然后通过CloseHandle(线程句柄)来关闭内核对象,最后将句柄置空
      

  3.   

    最好是在线程内通过标志判断或是响应发来的消息来结束线程,用TerminateThread申请的内存和资源都不能得到释放,除非万不得已,一般不要用
      

  4.   

    while(标识)
    {
       ......
    }