views:

88

answers:

2
class Thread
{
public:
    Thread ( DWORD (WINAPI * pFun) (void* arg), void* pArg)
    {
        _handle = CreateThread (
        0, // Security attributes
        0, // Stack size
        pFun,
        pArg,
        CREATE_SUSPENDED,
        &_tid);
    }
    ~Thread () { CloseHandle (_handle); }
    void Resume () { ResumeThread (_handle); }
    void WaitForDeath ()
    {
        WaitForSingleObject (_handle, 2000);
    }
private:
    HANDLE _handle;
    DWORD  _tid;     // thread id
};

How come the WaitForDeath() can kill the thread?

+1  A: 

The thread is not killed, it just dies by itself when the function passed as a parameter exits.

WaitForSingleObject waits for that termination.

Edouard A.
A: 

Actually WaitForDead will wait for the thread to finish (via normal function exit) or time out in 2 seconds and leave the thread alive. You may want to add a synchronization object (i.e. Win32 event) to signal the thread to terminate and have the thread check it periodically and exit if signaled.

Franklin Munoz