[fpc-pascal] Use sleep in thread

A. Fortuny aforsprl at gmail.com
Thu Mar 5 11:49:16 CET 2015


Le 25/02/2015 15:41, Xiangrong Fang a écrit :
> Hi All,
>
> Can I use Sleep() in a thread to give up cpu time to other threads 
> running at the same time, so as to adjust the relative "niceness" of a 
> group of workers working on the same subject (in which each thread 
> take part of the whole task).
>
> Thanks!
>
> Xiangrong
>
>
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal
Coming back to the initial message, I've had to solve a similar problem 
a year ago. A bunch of threads had to do do some job each one related to 
a database. Jobs to do were coming from the main thread (a service) and 
some results and messages where held and processed by the same main 
thread. The main problem was that all threads had to take care from 
incoming messages.

For tthese reasons I implemented the threads with a loop where the last 
instruction was a WaitForMultipleObjects. The events where hosted and 
set in the main thread which fired the events when something was to be 
done by the relevant thread. This way, when the thread had nothning to 
do, the WaitFor... passed the control to the kernel and entered a sleep 
state. But if an incoming job was posted, the event fired did awake the 
corresponding thread. Some other threads did not wait for any external 
job, so the WaitFor... was replaced by a simple Sleep. This helped me to 
implement an internal thread safe message queue. Another problem solved 
was a front end program using Indy and TCP/IP listener using non 
blocking sockets, to be reactive to more than 20 active TCP/IP clients 
sending messages for about 10 in a second for each client. The front end 
program managed all this incoming traffic showing that all client 
threads were working almost "at the same time". Using events the main 
program was able to send user commands to the "sleepeng" threads and 
seeing them be executed at once.

So using either Sleep or events depends on what the thread is supposed 
to do and what are the incoming signals if any. Using Sleep nothing can 
reach the sleeping thread whilst waiting for events stops the thread 
until something has to be done. On the other hand a periodical awake 
period using the WaitFor... timeout.

Antonio.

---
L'absence de virus dans ce courrier électronique a été vérifiée par le logiciel antivirus Avast.
http://www.avast.com





More information about the fpc-pascal mailing list