Locking mutex in one thread and unlocking it in the other

拟墨画扇 提交于 2019-12-23 07:28:39

问题


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.


回答1:


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.




回答2:


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.




回答3:


Some implementations do allow locking and unlocking threads to be different.

#include <iostream>
#include <thread> 
#include <mutex> 

using namespace std;

mutex m;

void f() {m.lock();   cout << "f: mutex is locked" << endl;}

void g() {m.unlock(); cout << "g: mutex is unlocked" << endl;}

main()
{
      thread tf(f);    /* start f                           */
      tf.join();       /* Wait for f to terminate           */
      thread tg(g);    /* start g                           */
      tg.join();       /* Wait for g to terminate           */
}

This program prints

f: mutex is locked g: mutex is unlocked

System is Debian linux, gcc 4.9.1. -std=c++11.



来源:https://stackoverflow.com/questions/4608843/locking-mutex-in-one-thread-and-unlocking-it-in-the-other

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!