JosephTLyons
JosephTLyons

Reputation: 2133

C++ Pthread Mutex Locking

I guess I'm a little unsure of how mutexs work. If a mutex gets locked after some conditional, will it only lock out threads that meet that same condition, or will it lock out all threads regardless until the mutex is unlocked?

Ex:

if (someBoolean)
    pthread_mutex_lock(& mut);

someFunction();

pthread_mutex_unlock(& mut);

Will all threads be stopped from running someFunction();, or just those threads that pass through the if-statement?

Upvotes: 0

Views: 2792

Answers (2)

user4815162342
user4815162342

Reputation: 155580

Will all threads be stopped from running someFunction();, or just those threads that pass through the if-statement?

Only the threads for which someBoolean is true will obtain the lock. Therefore, only those threads will be prevented from calling someFunction() while someone else holds the same lock.

However, in the provided code, all threads will call pthread_mutex_unlock on the mutex, regardless of whether they actually locked it. For mutexes created with default parameters this constitutes undefined behavior and must be fixed.

Upvotes: 2

nos
nos

Reputation: 229342

You need to call pthread_mutex_lock() in order for a thread to be locked. If you call pthread_mutex lock in thread A, but not in thread B, thread B does not get locked (and you have likely defeated the purpose of mutual exclusion in your code, as it's only useful if every thread follows the same locking protocol to protect your code).

The code in question has a few issues outlined below:

if (someBoolean)  //if someBoolean is shared among threads, you need to lock 
                  //access to this variable as well.
    pthread_mutex_lock(& mut);

someFunction(); //now you have some threads calling someFunction() with the lock
                //held, and some calling it without the lock held, which 
                //defeats the purpose of mutual exclusion.

pthread_mutex_unlock(& mut); //If you did not lock the *mut* above, you must not 
                             //attempt to unlock it.

Upvotes: 3

Related Questions