开发者

Check if thread is running

开发者 https://www.devze.com 2023-02-11 22:30 出处:网络
When I declare a HANDLE HANDLE hThread; I make a check to see if the thread is running, if (WaitForSingleObject(hThread, 0) == WAIT_OBJECT)

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(......)
 开发者_如何学Go }

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?


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消