let’s say i have a blocking method , let’s call in Block().
as i don’t want my main thread to block i might create a worker thread, that instead will call Block.
however, i have another condition.
i want the call to block to return in 5 seconds top, otherwise, i want to let the main thread know the call to Block failed and to exit the worker thread.
what would be the best solution to that scenario?
i thought something like that:
create a workher thread, in the worker thread to create a timer object with 5 seconds,
and in addition to call gettickcount before and after the call to Block and calculate the delta.
in addition i will define a boolean IsReturned indication whether the Block function returned already.
after the Block call to set it true.
according to that boolean in the Timer Function i decide how to proceed :
-
if the boolean is true i do nothing.
-
if the boolean is false i can queue an APC OnFailure or maybe signal Sucess event on the main thread, and exit the worker thread forcfully (the thing is i’m not sure if i can do that)
in addition after the block function return i check whether the delta is lett then 5 sec
and queue an APC OnSucess. (the question is does exiting the caller thread cancels the timer also ? cause basically after that the timer is useless )
p.s – if i can know for sure that i can cancel the worker thread within the timer function i don’t think i even need the gettickcount stuff.
thanks!
I would suggest using the boost::threads library for this. You can periodically check if the blocking thread is joinable (ie, still working) and then interrupt it after five seconds. You will then need to write the blocking function to handle that interruption and cleanly exit.
Edit: Check the Thread Management documentation for more interruption points and the definition for the boost threads class.
Edit2: If you don’t need to do any work in the main thread while waiting for the blocking thread to complete, and there is no convenient place to handle interrupts in
Block()you can explicitly kill the thread with something like this: