What happens if a posix mutex is unlocked while multiple threads are blocked on this mutex? - multithreading

thread 1:
lock mutex1
long time operation
unlock mutex1
thread2:
lock mutex1
...
thread3:
lock mutex1
...
thread4:
lock mutex1
...
threadn:
lock mutex1
...
When thread1 unlocks mutex1, which thread will be woken up? Is there a standard specification for it?

When you unlock a posix mutex using pthread_mutex_unlock, if several threads are waiting on the mutex only one of them will wake up.
The documentation states:
If there are threads blocked on the mutex object referenced by mutex
when pthread_mutex_unlock() is called, resulting in the mutex becoming
available, the scheduling policy shall determine which thread shall
acquire the mutex.

when thread1 unlock mutex1, which thread will be woken up?
One of the other threads that are currently blocked on the mutex. It is unspecified which of them.
Is there a standard specification for it?
No. Different systems may implement it in different ways. (Some might use a simple fifo order for waking the threads, others might use heuristics for deciding which thread to wake up).

Related

Can two wait operations executed by two separate threads on different semaphores be interleaved during execution?

I'm motivated with this citation from "Concepts in Programming Languages" by John C. Mitchell:
"Atomicity prevents individual statements of one wait procedure from being
interleaved with individual statements of another wait on the same semaphore."
Wait and signal operations need to be atomic which is often enforced by some "lower" level mechanism of acquiring lock - disabling interrupts, disabling preemption, test and set ... But, conceptually, how these locks can be in some way "private" for each semaphore instance?
In other words, is it allowed for example that one thread acquires lock at the beginning and later be preempted in the middle of executing wait operation on one semaphore, and after that another thread acquires lock at the beginning of wait operation on some other semaphore and enters in the body of its wait operation, so that two thread are in the wait operations on different semaphores at the same time? Or, shortly, whether the wait operations on two different semaphores mutually exclusive?
My point is, if thread acquires lock in wait operation on one semaphore s1, is it allowed for another thread to acquire lock at the same time in wait operation on another semaphore s2? I'm emphasizing that these are two different semaphore instances, not the same one.
For example:
class Semaphore {
...
public:
void wait();
...
}
void Semaphore::wait(){
lock();
//POINT OF CONTINUATION FOR THREAD 2!//
if(--val<0){
//POINT OF PREEMPTION FOR THREAD 1!//
block();
}
unlock();
}
Semaphore s1;
Semaphore s2:
...
So...
Is it allowed at some point of execution that one thread be preempted while executing wait operation on semaphore s1 at //POINT OF PREEMPTION FOR THREAD 1!// , and control transfers to another thread which executes wait operation of semaphore s2 at //POINT OF CONTINUATION FOR THREAD 2!//...
...or...
Is it allowed for instructions of wait operation from one semaphore to be interleaved with instruction of wait operation from another semaphore?
..or...
Is it allowed for more than one threads to be in wait operations on different semaphores at the same time?
Sorry for my wordiness but I really struggle to clarify my question. Thanks in advance.
Yes, it's allowed. One of the reasons you would use two different locks, rather than using the same lock for everything, is to avoid unnecessary dependencies like this.
Is it allowed for instructions of wait operation from one semaphore to be interleaved with instruction of wait operation from another semaphore?
Absolutely.
Is it allowed for more than one threads to be in wait operations on different semaphores at the same time?
Absolutely.
Prohibiting any of these things would hurt performance significantly for no benefit. Contention is the enemy of multi-threaded performance.

Lock Holder Preemption

Could you have the following scenario in concurrent programs?
suppose a thread acquires a lock to execute a critical section.Then before the critical section is executed the processor preempts the thread. The new thread that comes for execution needs the lock from the old thread (that was preempted). So the current thread can't proceed (hangs until it get preempted). Is there a mechanism in Operating systems to not let threads preempted until the lock is released?
It is possible for a thread holding a mutex to be preempted while executing a critical section. If the thread that the OS switches to tries to acquire that mutex and finds that it is already locked, then that thread should be context switched out immediately. The thread scheduler should be smart enough to not switch back to that thread until it has switched back to the thread holding the mutex and the mutex is released.
If you are writing Kernel code then yes, there are mechanisms for preventing a thread to preempt.
For standard code there is no such thing. Some operations are atomic and are ensured atomic by the compiler and kernel but right after those operations the thread may be preempted and it can remain preempted for an undetermined amount of time (unless the system is a real-time sistem).

How can I grant ownership of a mutex to a specific thread?

Imagine I have a mutex locked. There is unlimited number of other threads waiting to lock the mutex. When I unlock the mutex, one of those threads will be chosen to enter the critical section. However I have no control over which one. What if I want specific thread to enter the critical section?
I am prety sure this cannot be done using POSIX mutex, however, can I emulate the behaviour using different synchronisation object(s)?
You can use a mutex, a condition variable and a thread id to achive that.
Before unlocking the mutex the thread sets the target thread id, broadcasts the condition variable and releases the mutex. The waiting threads wake up, lock the mutex and check whether the target thread id equals to this thread id. If not the thread goes back to wait.
An optimization to this method to avoid waking up all waiting threads just to check the target thread id and then go back to wait would be to use a separate condition variable for each waiting thread. This way the signaling thread would notify the condition variable of the particular target thread.
Another option is to use signals sent to a particular thread. Let's say we use SIGRTMINfor this purpose. First, all threads block this signal at the start, so that the signal becomes pending and doesn't get lost when the thread isn't waiting for it. When a thread wants to lock the mutex it first calls sigwait() which atomically unblocks SIGRTMIN and waits for it or delivers an already pending one. Once the thread received the signal it can proceed and lock the mutex. The signaling thread uses pthread_kill(target_thread_id, SIGRTMIN) to wake up a particular thread.

Does a thread lock another thread?

Singularity - If a thread managed to lock a mutex, it is assured that no other thread will be able to lock the thread until the original thread releases the lock.
Non-Busy Wait - If a thread attempts to lock a thread that was locked by a second thread, the first thread will be suspended (and will not consume any CPU resources) until the lock is freed by the second thread. At this time, the first thread will wake up and continue execution, having the mutex locked by it.
From: Multi-Threaded Programming With POSIX Threads
Question: I thought threads lock the mutex variables. Threads don't lock other threads?
What do the bold statements above mean? How can one thread lock other thread?
Corrections:
If a thread managed to lock a mutex, it is assured that no other thread will be able to lock the mutex until the original thread releases the lock.
Non-Busy Wait - If a thread attempts to lock a mutex that was locked by a second thread, the first thread will be suspended (and will not consume any CPU resources) until the lock is freed by the second thread. At this time, the first thread will wake up and continue execution, having the mutex locked by it.
It's a good thing you don't take for granted whatever you read on the internet, also I give you thumbs up for paying attention to what you read.

some questions regarding pthread_mutex_lock

when a thread1 already acquired a lock on mutex object, if thread2 tries to acquire a lock on the same mutex object, thread2 will be blocked.
here are my questions:
1. how will thread2 come to know that mutex object is unlocked?
2. will thread2 try to acquire lock at predifined intervals of time?
I sense a misunderstanding of how a mutex works. When thread 2 tries to acquire a mutex that is already owned by thread 1, the call that tries to take the mutex will not return until the mutex becomes available (unless you have a timeout with trylock() variant).
So thread 2 does not need to loop there and keep trying to take the mutex (unless you're using a timeout so you can abort trying to take the mutex based on some other condition like a cancel condition).
This is really OS dependant, but what usually happens is that thread2 gets suspended and put on a wait list maintained by the mutex. When the mutex becomes available, a thread on the mutex's waitlist gets removed from the list and put back on the list of active threads. The OS can then schedule it like it usually would. thread2 is totally quiescent until it can acquire the mutex.

Resources