C++线程互斥锁

C++ Pthread Mutex Locking

本文关键字:线程 C++      更新时间:2023-10-16

我想我有点不确定mutex是如何工作的。 如果mutex在某些条件后被锁定,它是只锁定满足相同条件的线程,还是会锁定所有线程,直到mutex解锁?

前任:

if (someBoolean)
pthread_mutex_lock(& mut);
someFunction();
pthread_mutex_unlock(& mut);

会停止所有线程运行someFunction();,还是只停止那些通过 if 语句的线程?

您需要调用pthread_mutex_lock()才能锁定线程。如果在线程 A 中调用pthread_mutex锁,但不在线程 B 中调用,则线程 B 不会被锁定(并且您可能已经破坏了代码中互斥的目的,因为只有当每个线程都遵循相同的锁定协议来保护代码时,它才有用(。

有问题的代码有几个问题,概述如下:

if (someBoolean)  //if someBoolean is shared among threads, you need to lock 
//access to this variable as well.
pthread_mutex_lock(& mut);
someFunction(); //now you have some threads calling someFunction() with the lock
//held, and some calling it without the lock held, which 
//defeats the purpose of mutual exclusion.
pthread_mutex_unlock(& mut); //If you did not lock the *mut* above, you must not 
//attempt to unlock it.

是停止所有线程运行someFunction();,还是只阻止那些通过 if 语句的线程?

只有someBoolean为 true 的线程才能获得锁。因此,只有这些线程才能在其他人持有相同锁的情况下调用someFunction()

但是,在提供的代码中,所有线程都将在互斥锁上调用pthread_mutex_unlock,无论它们是否实际锁定了互斥锁。对于使用默认参数创建的互斥锁,这构成了未定义的行为,必须修复。