windows 检查线程是否正在运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5031029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if thread is running
提问by user3234
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.
但是第一次检查线程是否正在运行时失败了。怎么做到呢?我认为我唯一需要的是以hThread
某种方式将信号设置为信号状态。
Edit
编辑
I have found something like this
我发现了这样的东西
hThread = CreateEvent(0, 0, 1, 0); //sets to handle to signaled
Do you agree with this?
你同意吗?
回答by David Heffernan
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
.
一旦您知道它已经开始(hThread
不是NULL
),那么您可以使用WaitForSingleObject
您已经知道的方法或使用GetExitCodeThread
.
回答by J?rgen Sigvardsson
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.
您的线程句柄未初始化。您不能WaitForSingleObject()
在垃圾句柄上使用。您是否试图告诉之前创建的线程的状态,并在它死后重新启动它?然后你需要跟踪第一个线程句柄。
回答by Alex F
Possibly you mean GetExitCodeThread
function.
可能你的意思是GetExitCodeThread
功能。
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.
当线程完成时,线程句柄变为有信号。这允许使用 Wait* 操作等待线程结束。您的代码创建事件句柄,而不是线程。