English 中文(简体)
检查线程是否正在运行
原标题:Check if thread is running

当我声明HANDLE时

HANDLE hThread;

我检查线程是否正在运行,

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

但它第一次检查线程是否正在运行时失败。如何做到这一点?我认为我唯一需要的就是以某种方式将hThread设置为信号状态。

Edit

我发现了这样的东西

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

你同意这一点吗?

问题回答

看起来您实际上并不想测试线程是否完成,而是想知道它是否已经启动。您通常会按照以下方式执行此操作:

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

一旦您知道它已经启动(hThread而不是NULL),您就可以使用您已经知道的WaitForSingleObject方法或GetExitCodeThread

您的线程句柄未初始化。不能在垃圾句柄上使用WaitForSingleObject()。您是否试图告知先前创建的线程的状态,并在线程死亡时重新启动它?然后,您需要跟踪第一个线程句柄。

可能你的意思是GetExitCodeThread函数。

编辑

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

线程句柄在线程完成时发出信号。这允许使用wait*操作等待线程结束。您的代码创建事件句柄,而不是线程。





相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...

热门标签