Locking mutex in one thread and unlocking it in the other

As user562734's answer says, the answer is no - you cannot unlock a thread that was locked by another thread.

To achieve the reader/writer synchronisation you want, you should use condition variables - pthread_cond_wait(), pthread_cond_signal() and related functions.


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.

Tags:

Mutex

Pthreads