Click to See Complete Forum and Search --> : threads and sleep


Red Squirrel
September 4th, 2008, 07:19 PM
I read in another thread that using sleep or usleep causes not only one thread to sleep, but the whole program. Is there an alternative way to make just the one thread its called from sleep instead of the whole program?

Arjay
September 4th, 2008, 08:58 PM
In general using sleep within a thread will only cause that thread to sleep and not the whole program.

The exception to this is when the sleeping thread has obtained a lock and other thread(s) are waiting to obtain the lock - the end effect is that the waiting thread(s) are essentially sleeping too.

The use of sleep should be avoided. Sometimes it is helpful to yield the remainder of a time slice by using a sleep(0), but usually times where sleep has been used can often be resolved by proper thread synchronization.

ishaypeled
September 5th, 2008, 05:25 AM
The use of sleep should be avoided. Sometimes it is helpful to yield the remainder of a time slice by using a sleep(0), but usually times where sleep has been used can often be resolved by proper thread synchronization.
You don't even need sleep(0) for that, simply use sched_yield to achieve the same goal.

Arjay
September 5th, 2008, 11:11 AM
You don't even need sleep(0) for that, simply use sched_yield to achieve the same goal.Sorry, I was referring to the Windows api.

lipun4u
October 9th, 2008, 09:12 AM
It depends....

no thread should use sleep(n) in its critical section...which will reduce the performance.

some times sleep() is used to avoid the situation of pooling which eats unnecessary CPU cycles.

Lindley
October 9th, 2008, 09:17 AM
I was taught that sched_yield was only to be used by the threading implementation, and that *any* use of it by a client program was a bug.

Makes sense to me----either you want to wait for a specific event, in which case a thread condition wait, mutex, or spinlock is appropriate, or else you want to make progress. Simply yielding control without specifying *why* you're doing so is pretty useless.