which sleep methods should be used in threads ?

Please discuss general Delphi programming topics here.

which sleep methods should be used in threads ?

Postby actalk » July 20th, 2008, 11:29 am

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.
actalk
Junior Member
Junior Member
 
Posts: 29
Joined: October 5th, 2007, 3:56 pm

Postby Kambiz » July 20th, 2008, 2:10 pm

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.
Kambiz
User avatar
Kambiz
Administrator
Administrator
 
Posts: 2429
Joined: March 7th, 2003, 7:10 pm

Postby actalk » July 20th, 2008, 3:28 pm

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
actalk
Junior Member
Junior Member
 
Posts: 29
Joined: October 5th, 2007, 3:56 pm

Postby Kambiz » July 21st, 2008, 11:59 am

This is the solution:

Code: Select all
FTerminateEvent.WaitFor(ItemInterval);
if Terminated then Exit;
Kambiz
User avatar
Kambiz
Administrator
Administrator
 
Posts: 2429
Joined: March 7th, 2003, 7:10 pm


Return to Delphi Programming

Who is online

Users browsing this forum: No registered users and 5 guests

cron