I try to change a sleep() function in a thread to pthread_cond_timedwait() so suspension can be stopped from another thread if it is needed. My question is about efficiency. Because as I understand when using sleep() the thread is passivly waiting so no additional cpu usage occures. What does the scheduler do with a mutex locked thread? Is it the same as with sleep() or is it actively waiting in this case? Because I use potentially a lot of threads which would be suspended for a long period of time (minutes, hours or maybe days) I fear I might use unnecessary cpu time.
-
Question is unclear. Are you interested in condition variables or mutexes? – SergeyA Sep 16 '21 at 17:12
-
Sorry my understanding is that if a thread is waiting for a condition variable it is in a mutex lock. I'm new to that whole concept so I might be wrong @SergeyA – notAuser Sep 16 '21 at 17:15
-
Not really. It is waiting on a signal that variable was changed. The mutex is only auxiliary, as it prevents several threads try to access the variable once the condition has been signaled. – SergeyA Sep 16 '21 at 17:25
-
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 23 '21 at 13:06
2 Answers
Here's the best way to distill down the behavior of pretty much all multi-threaded OSes without regard for sweeping generalizations:
A thread is usually represented as a data structure that stores context. The scheduler keeps a list of thread structs which are currently "runnable." If a thread is taken off the "runnable" list, it will not be scheduled to run on any available CPU.
A mutex is usually implemented as a reference to a thread struct which owns the mutex, and a list of threads which are waiting for it. A thread cannot be on both a wait list, and the scheduler's runnable list simultaneously. Thus a thread waiting on a mutex cannot be scheduled, and cannot take CPU resources.
There are caveats and details. For example on a multi CPU system, the mutex implementation might actually allow for a short period of "spin waiting" before being placed on a wait queue. This covers cases where a lock might only be held briefly by another thread on another CPU, in which case a full context switch might be more expensive. In general though, you can assume a blocked thread will not be runnable from the scheduler's point of view.

- 2,426
- 3
- 14
No, waiting on a mutex doesn't use CPU time. Mutexes are implemented in the kernel, so it puts the thread to sleep until the mutex is unlocked.

- 741,623
- 53
- 500
- 612
-
1Maybe. See https://stackoverflow.com/questions/19863734/what-is-pthread-mutex-adaptive-np Other OSes also use adaptive mutexes that spin for a bit before going to sleep. – Andrew Henle Sep 16 '21 at 17:14