C++线程互斥锁
C++ Pthread Mutex Locking
我想我有点不确定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
,无论它们是否实际锁定了互斥锁。对于使用默认参数创建的互斥锁,这构成了未定义的行为,必须修复。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- CoInitialize()在单独的线程上崩溃而不返回
- c++中的线程池
- 线程之间的布尔停止信号
- 为什么std::async使用同一个线程运行函数
- 用于矢量处理的多个线程
- C++为线程工作动态地分割例程
- 为什么我不能在 while 循环中创建线程?