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?
Printable View
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?
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.
You don't even need sleep(0) for that, simply use sched_yield to achieve the same goal.Quote:
Originally Posted by Arjay
Sorry, I was referring to the Windows api.Quote:
Originally Posted by ishaypeled
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.
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.