Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking mutex in one thread and unlocking it in the other

Tags:

mutex

pthreads

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.

like image 651
Eugene Pakhomov Avatar asked Jan 05 '11 20:01

Eugene Pakhomov


People also ask

Can mutex lock be unlock by different thread?

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.

Can two threads lock the same mutex?

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.

What happens if you unlock an unlocked 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.

What happens if 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.


1 Answers

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.

like image 141
user562374 Avatar answered Jan 04 '23 11:01

user562374