当我对已经锁定的 pthread_mutex_t 执行 pthread_mutex_init 时会发生什么?

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

我的互斥量 class 已定义:-

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);
    }
};

我尝试应用互斥来使用这个 class 的函数是这样的:-

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

这样,当构造函数被调用时,互斥锁被初始化并尝试获取该互斥锁上的锁。当它超出该函数的范围时,它会自动被销毁。

但是如果一个线程锁定了互斥量,另一个线程试图 运行 pthread_mutex_init 在它上面,到底会发生什么?有锁的线程会被覆盖吗?

很简单,来自 POSIX.1-2013:

Attempting to initialize an already initialized mutex results in undefined behavior.

这就是为什么您有另一种初始化互斥锁的方法:

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

除此之外,从逻辑上讲,您的class似乎很值得怀疑。您真的想要 one 全局锁 Mutex 的所有用户,无论他们在做什么吗?您应该使用细粒度的锁,否则您将通过 software lockout.

人为地限制您自己的可扩展性