Linux – What is Mutex Get and Release Order?

What is Mutex Get and Release Order?… here is a solution to the problem.

What is Mutex Get and Release Order?

I know what Mutex does. But now I’m confused about its timing. I am referring specifically to in the Linux kernel code.

For example, we have 3 threads (assuming they are on the same processor and are all normal tasks with the same priority). Threads 1, 2, and 3 try to get Mutex, but only thread 1 gets it. Threads 2 and 3 are blocked and go to sleep. Then thread 1 finishes his job and unlocks Mutex.

So here’s my question: what happens at this moment? Will Thread 1 continue to execute because its scheduled time slices have not been used up? Or is it because it’s the second thread that wants to acquire the lock, so thread 2 immediately acquires the lock and starts executing? Or does thread 3 immediately acquire the lock and start executing because it is assumed to be the next run of the task scheduler (let’s assume this)? What happens?

Solution

Once thread 1 releases the lock, what happens next is nondeterministic. Any situation you outline above is possible.

If your application requires a specific order between threads, you might want to try to communicate more explicitly between threads. In C, you can do this using pipe().

But in general, performance is best if you accept the confusion and let the scheduler choose.

Related Problems and Solutions