Will this code be correct and portable?
void* aThread(void*)
{
while(conditionA)
{
pthread_mutex_lock(mutex1);
//do something
pthread_mutex_unlock(mutex2);
}
}
void* bThread(void*)
{
while(conditionB)
{
pthread_mutex_lock(mutex2);
//do something
pthread_mutex_unlock(mutex1);
}
}
In the actual application I have three threads - two for adding values to an array and one for reading them. And I need the third thread to display the contents of the array right after one of the other threads adds a new item.
NO -- but a SEMAPHORE with a value of 1 can be just like a mutex, and can be unlocked from a different thread. You may need to protect operations on the semaphore with a mutex to stop it's value going above 1 however.
Only one thread can own the mutex at a time. If a second thread tries to "acquire" ownership, it will block (be suspended) until the owning thread "releases" the mutex. If several threads are all waiting to acquire the same mutex, they will all be released simultaneously when the owning thread releases the mutex.
If a thread attempts to unlock a mutex that it has not locked or a mutex that is unlocked, an error is returned. If the mutex type is PTHREAD_MUTEX_DEFAULT, attempting to unlock the mutex if it was not locked by the calling thread results in undefined behavior.
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.
It is not. If thread A gets to mutex_unlock(2) before thread B got to mutex_lock(2), you are facing undefined behavior. You must not unlock another thread's mutex either.
The pthread_mutex_lock Open Group Base Specification says so:
If the mutex type is PTHREAD_MUTEX_NORMAL [...] If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, undefined behavior results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With