Page 1 of 1

which sleep methods should be used in threads ?

PostPosted: July 20th, 2008, 11:29 am
by actalk
Hello !

I try WaitForSingleObject(tempEvent, tempInterval) but I can not make correct timing.

I think SysyUtils.Sleep function is not interruptable.

I need a interruptabe sleep method. it should not use much more system resource because there are alot of threads and they use sleep 1000s times in a day ... ( may be a bad design :) ).

1 second or half second is not imortant for me.

I need any clue about CreateEvent and WaitForSingleObject
or
other interruptable sleep methods.

thanks.

PostPosted: July 20th, 2008, 2:10 pm
by Kambiz
If you just need to wait for a specific period of time inside a thread, Sleep API is the most appropriate one.

But as you already have mentioned, to wait for maximum a period of time you have to use something like event.
Create the event in manual reset mode and initially reset it:

Code: Select all
EventHandle := CreateEvent(nil, True, False, nil);


Inside your thread wait for the event:

Code: Select all
WaitForSingleObject(EventHandle, TheInterval);


Whenever you need to resume the thread regardless of wait interval, call:

Code: Select all
PulseEvent(EventHandle);


And finally, before terminating the thread, call:

Code: Select all
SetEvent(EventHandle);


By the way, take a look at Waitable Timer Objects on Windows API. Maybe you can use this object inside threads.

PostPosted: July 20th, 2008, 3:28 pm
by actalk
Thank you Kambiz.

now I am trying a bit diffrent one.
but I think Delphi uses same code like in yours reply.

When i stop the threads... rarely program hangs (suspends)
but I dont know where it suspends and why...

Code: Select all
on decleration of the thread
  FTerminateEvent: TEvent;


Code: Select all
on Create of thread
  FTerminateEvent := TEvent.Create(nil, False, False, '');
second parameter differs from yours.

Code: Select all
on destroy
  FTerminateEvent.Free;


Code: Select all
on  tryStop procedure of the thread
  Terminate;
  FTerminateEvent.SetEvent;
instead of PulseEvent

Code: Select all
on the Execute method
 FTerminateEvent.WaitFor(ItemInterval);
same

PostPosted: July 21st, 2008, 11:59 am
by Kambiz
This is the solution:

Code: Select all
FTerminateEvent.WaitFor(ItemInterval);
if Terminated then Exit;