African_king
African_king

Reputation: 187

If a mutex is already locked how can pthread_mutex_lock(pthread_mutex_t *mutex); block the thread and still return a value at the same time?

The mutex object referenced by mutex shall be locked by calling pthread_mutex_lock(). If the mutex is already locked, the calling thread shall block until the mutex becomes available. This operation shall return with the mutex object referenced by mutex in the locked state with the calling thread as its owner.

My question is, if the mutex is already locked, and we call pthread_mutex_lock(), does this function return a value even though the thread is blocked, or does it return the value after the block?

Illustration of my question.

What happens? When does pthread_mutex_lock() return its value to the second thread?

Is it after the mutex is unlocked by the 1st thread? Or, does it return its value then blocks the 2nd thread?

Upvotes: 2

Views: 3666

Answers (2)

Emmef
Emmef

Reputation: 522

Short answer to your question: pthread_mutex_lock(&mutex) will not return a value until the thread unblocks after it gets the lock. However, your code just sees a function call and perceives a direct return value.

Here is some more explanation.

About return values:

  • If function pthread_mutex_lock(&mutex) returns zero, you can rely on the fact that your thread has locked mutex: don't forget to unlock it!

  • If the method returns a non-zero error code, the mutex is NOT locked by your thread, and you should not do a corresponding unlock.

The perspective of your code calling pthread_mutex_lock(&mutex):

  • If mutex was NOT locked, pthread_mutex_lock(&mutex) will lock mutex and return zero immediately.

  • If mutex was already locked by another thread, the function will block until your thread gets the lock on mutex and then return zero. However, the perspective of your code just sees a function call that returns a value: code in a thread doesn't notice its blocked. Unless, of course, you put timers around the function call.

  • If the mutex was already locked by your thread, the function deadlocks. By default, a mutex is not re-entrant and you must avoid to lock it in an already locked context, e.g. recursion. I leave it out of scope how to do re-entrant locking. In this case, the function simply never returns.

  • If mutex cannot be locked for whatever reason, the function immediately returns with a non-zero error code.

Upvotes: 5

Quimby
Quimby

Reputation: 19223

The description means the function will block until the mutex becomes unlocked (by its previous owner) then it locks the mutex and only after that returns. Now, the caller of the function is owner of the lock.

Upvotes: 2

Related Questions