Reputation: 13
How to sleep at some time, in milliseconds, the posix pthread ? which approach is best suited for this: use usleep function or pthread_cond_timedwait.
Upvotes: 1
Views: 9315
Reputation: 105876
You're staying in a hotel. You want to wake up after some hours. If you want to use the swimming pool in the morning all by yourself, you want the hotel manager to only wakeup if there is either something important (spurious wakeup from pthread_cond_wait
) or if the hotel pool is yours (the mutex has been locked).
But if you just want to wake up after some hours, you set your alarm clock and when you wake up, you check whether the alarm has gone off or you can sip another hour. You don't care for other resources, just whether the time has passed. You simply nanosleep()
.
If you simply want to sleep, sleep by using usleep
or nanosleep
. pthread_cond_wait
has an overhead, since it locks a mutex when it returns. If that mutex isn't available for some time you will sleep longer than you originally wanted, or even forever, if the other thread has some problem or deadlock.
That being said, if you wait for a mutex-protected resource and want to acquire a mutex immediately after your thread wakes up, you should use a condition variable.
If you use C++11 try std::this_thread::sleep_for
. However, don't mix C++11 thread data structures (thread, mutex, condition variables) with POSIX' ones.
Upvotes: 7