我在概念化如何unique_lock
应该是跨线程操作。我尝试制作一个快速示例来重新创建我通常会使用的东西condition_variable
for.
#include <mutex>
#include <thread>
using namespace std;
mutex m;
unique_lock<mutex>* mLock;
void funcA()
{
//thread 2
mLock->lock();//blocks until unlock?Access violation reading location 0x0000000000000000.
}
int _tmain(int argc, _TCHAR* argv[])
{
//thread 1
mLock = new unique_lock<mutex>(m);
mLock->release();//Allows .lock() to be taken by a different thread?
auto a = std::thread(funcA);
std::chrono::milliseconds dura(1000);//make sure thread is running
std::this_thread::sleep_for(dura);
mLock->unlock();//Unlocks thread 2's lock?
a.join();
return 0;
}
unique_lock
不应同时从多个线程访问。它并不是以这种方式设计为线程安全的。相反,多个unique_lock
s(局部变量)引用相同的全局变量mutex
。只有mutex
其本身被设计为可以同时被多个线程访问。即便如此,我的声明也不包括~mutex()
.
例如,人们知道mutex::lock()
可以被多个线程访问,因为它的规范包括以下内容:
同步: Prior unlock()
对同一对象的操作应同步于(4.7)此操作。
where 同步于是 4.7 [intro.multithreading](及其子条款)中定义的术语。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)