终止使用 QueueUserWorkItem(win 32/nt5) 创建的线程池中长时间运行的线程
我正在Win32 nt5环境中编程。
我有一个将被多次调用的函数。每个调用都是原子的。我想使用 QueueUserWorkItem 来利用多核处理器。
我遇到的问题是我只想给该函数 3 秒的时间来完成。如果 3 秒内没有完成,我想终止该线程。
目前我正在做这样的事情:
HANDLE newThreadFuncCall= CreateThread(NULL,0,funcCall,&func_params,0,NULL);
DWORD result = WaitForSingleObject(newThreadFuncCall, 3000);
if(result == WAIT_TIMEOUT)
{
TerminateThread(newThreadFuncCall,WAIT_TIMEOUT);
}
我只是生成一个线程并等待 3 秒或它完成。有没有办法做类似的事情,但使用 QueueUserWorkItem 来排队工作?
I am programming in a Win32 nt5 environment.
I have a function that is going to be called many times. Each call is atomic. I would like to use QueueUserWorkItem
to take advantage of multicore processors.
The problem I am having is I only want to give the function 3 seconds to complete. If it has not completed in 3 seconds I want to terminate the thread.
Currently I am doing something like this:
HANDLE newThreadFuncCall= CreateThread(NULL,0,funcCall,&func_params,0,NULL);
DWORD result = WaitForSingleObject(newThreadFuncCall, 3000);
if(result == WAIT_TIMEOUT)
{
TerminateThread(newThreadFuncCall,WAIT_TIMEOUT);
}
I just spawn a single thread and wait for 3 seconds or it to complete. Is there anyway to do something similar to but using QueueUserWorkItem
to queue up the work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ThreadPool不不适合长时间运行的操作,或者在您想要显式控制线程的情况下。
此外,您应该考虑重构您的函数,以允许使用中止标志正常退出,而不是强制终止线程。
The ThreadPool is not a candidate for long-running operations or in instances where you want explicit control over the thread.
In addition, you should consider refactoring your function to allow a graceful exit using an abort flag rather than terminating the thread forcefully.
不要使用线程轮询。而是使用后台线程,以及一个用于监视器的线程。只需创建线程,让操作系统担心多核处理器或任何处理器类型。
Don't use Thread-Poll. Instead use Background Thread, and one more thread for monitor. Just create the thread and let operating system to worry about multicore processors or whatever the processor type.