简体   繁体   English

在已经锁定的pthread_mutex_t上执行pthread_mutex_init时会发生什么?

[英]What happens when I do a pthread_mutex_init on an already locked pthread_mutex_t?

My mutex class is defined:- 我的互斥锁类定义为:

class Mutex{
    static pthread_mutex_t mutex;
public:
    Mutex(){
        pthread_mutex_init(&mutex, NULL);
        while(pthread_mutex_trylock(&mutex)){
            sleep(2000);
        }
    }
    virtual ~Mutex(){
        pthread_mutex_unlock(&mutex);
        pthread_mutex_destroy(&mutex);
    }
};

The functions I am trying to apply the mutual exclusion to use this class like this:- 我正在尝试使用互斥的函数来使用此类,例如:

void doSomething(){
    Mutex mutex;
    // do something
}

This way when the constructor is called, the mutex is initialized and it tries to obtain the lock on that mutex. 这样,在调用构造函数时,互斥量将被初始化,并尝试获取该互斥量的锁。 And when it goes out of scope from that function, it automatically gets destroyed. 并且当它超出该功能的范围时,它将自动被销毁。

But if one thread has a lock on the mutex, another thread tries to run pthread_mutex_init on it, what exactly happens? 但是,如果一个线程在互斥锁上有一个锁,则另一个线程尝试在该线程上运行pthread_mutex_init ,究竟发生了什么? Will the thread that has the lock be overridden? 具有锁的线程会被覆盖吗?

Pretty easy, from POSIX.1-2013 : POSIX.1-2013开始非常简单:

Attempting to initialize an already initialized mutex results in undefined behavior. 尝试初始化已经初始化的互斥锁会导致未定义的行为。

That's why you have an alternative way of initializing mutexes: 这就是为什么您有另一种初始化互斥锁的方法:

// in your .cpp somewhere
pthread_mutex_t Mutex::mutex = PTHREAD_MUTEX_INITIALIZER;

Apart from this, logically speaking, your class seems very questionable. 除此之外,从逻辑上讲,您的课程似乎非常有问题。 Do you really want to have one global lock for all users of Mutex , no matter what they're doing? 您是否真的想为Mutex所有用户使用一个全局锁,而不管他们在做什么? You should employ fine grained locks, or you'll artificially limit your own scalability via software lockout . 您应该使用细粒度的锁,否则将通过软件锁定人为地限制自己的可伸缩性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM