Originally Posted by
Abs
Interesting, I didn't know you could set a mutex to span multiple processes... I always thought the pthread library was more specific to the threads located in a single process. But I guess now that I think about the use of sem_init etc... and that it can span processes while being included in the pthread library it makes sense. Thanks
Well, consider what a pthread_mutex actually is. It looks kind of like this:
Code:
struct pthread_mutex_t
{
volatile sig_atomic_t spinlock;
int lock_count;
int wait_count;
wait_queue_head *waiting_threads;
};
When a thread or process attempts to lock the mutex, it first gains the spinlock. Then it checks the lock count -- if the lock is unlocked, it increments the count, then unlocks the spinlock. On the other hand, if the lock was locked, the process puts itself on the wait queue, increments the wait count, then unlocks the spinlock while simultaneously sleeping. On Linux, that last step is achieved with a futex.
When the process holding the mutex unlocks it, it first locks the spin lock, then decrements the lock_count. If the lock_count becomes zero, it checks the wait count (while still holding the spinlock). If it's greater than zero, it dequeues all the processes on the wait queue and wakes them up, sets the wait_count to zero, decrements the lock_count, then unlocks the spinlock.
Being able to do this across processes depends on having a method of placing other processes on the wait queue, and telling them to wake up. On Linux, this is done with futexes. Not all implementations of pthreads support inter-process mutexes, but Linux does.