Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do threads sleep when waiting on a locked mutex?

Do threads blocked by a std::mutex::lock() or a condition variable sleep in a way that frees the core for other processes, or am I required to manually put these threads to sleep? And if true, would std::mutex::try_lock() allow for a way to spin the thread without sleeping?

The reason I ask: I want to have three states for threads in my thread pool that are unused: spinning for 2 milliseconds, then locked by a mutex for 250-ish milliseconds (assuming this lets them sleep and unhog the core), then finally being deallocated.

I want to avoid calling sleep manually if I can help it, tuning the sleep duration would be hard. So can I safely leave that to the mutex?

like image 763
Anne Quinn Avatar asked Dec 27 '18 21:12

Anne Quinn


People also ask

What happens when you try to lock a locked mutex?

Mutexes are used to protect shared resources. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it.

What happens if you don't unlock a mutex?

If you don't, then a typical mutex is held in process memory and will simply cease to exist along with anything that might have access to it when the process terminates.

What happens when mutex lock is used more than once?

If a thread which had already locked a mutex, tries to lock the mutex again, it will enter into waiting list of that mutex which results in deadlock.

Can mutex cause deadlock?

Mutexes are used to prevent multiple threads from causing a data race by accessing shared resources at the same time. Sometimes, when locking mutexes, multiple threads hold each other's lock, and the program consequently deadlocks. Four conditions are required for deadlock to occur: Mutual exclusion.


2 Answers

That is implementation specific; the C++ standard does not speak to it directly.

In practice, mutexes may use a combination of spin lock and full sleep. Sleeping and waking up is relatively expensive, and a compiler may write the locks to spin for a few ms before putting the thread to sleep.

No C++ implementation on a major phone, PC or big iron is going to spin lock indefinitely however. I could imagine some embedded system doing so, but have not personally encountered one.

like image 189
Yakk - Adam Nevraumont Avatar answered Nov 08 '22 08:11

Yakk - Adam Nevraumont


Yes. Such blocked threads sleep and don't take up any CPU cycles.

like image 42
Jesper Juhl Avatar answered Nov 08 '22 10:11

Jesper Juhl