user3234
user3234

Reputation: 103

Check if thread is running

When I declare a HANDLE

HANDLE hThread;

I make a check to see if the thread is running,

  if (WaitForSingleObject(hThread, 0) == WAIT_OBJECT)
  {
       //Thread is not running.
  }
  else
  {
       hThread = CreateThread(......)
  }

But it fails for the first time to check if the thread is running. How can it be done? I think the only thing i need is set the hThread to signaled state somehow.

Edit

I have found something like this

hThread = CreateEvent(0, 0, 1, 0); //sets to handle to signaled

Do you agree with this?

Upvotes: 0

Views: 7282

Answers (3)

David Heffernan
David Heffernan

Reputation: 612954

It seems that you don't actually want to test whether the thread is finished, but instead want to know whether or not it has started. You would normally do this as follows:

HANDLE hThread = NULL;//do this during initialization
...
if (!hThread)
   hThread = CreateThread(......);

Once you know it has started (hThread not NULL) then you can test for it being completed with the WaitForSingleObject method that you are already aware of, or with GetExitCodeThread.

Upvotes: 4

Alex F
Alex F

Reputation: 43311

Possibly you mean GetExitCodeThread function.

Edit.

hThread = CreateEvent(0, 0, 1, 0); //sets to handle to signaled

Thread handle becomes signaled when thread finished. This allows to wait for thread end using Wait* operations. Your code creates event handle, and not thread.

Upvotes: 1

Jörgen Sigvardsson
Jörgen Sigvardsson

Reputation: 4887

Your thread handle is uninitialized. You can't use WaitForSingleObject() on garbage handles. Are you trying to tell the status of a thread that has been created earlier, and restart it if it has died? Then you need to keep track of the first thread handle.

Upvotes: 2

Related Questions