views:

158

answers:

2

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?

+5  A: 

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.

Adam Robinson
A: 

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.

Mohanavel