C++ 互斥锁的所有权不会转移到另一个线程 当读卡器得到锁时
输出与我预期的不同 我所期望的是作者和读者交替拥有锁 这种行为正常吗C++ 互斥锁的所有权不会转移到另一个线程 当读卡器得到锁时,c++,multithreading,boost,mutex,C++,Multithreading,Boost,Mutex,输出与我预期的不同 我所期望的是作者和读者交替拥有锁 这种行为正常吗 是否有锁定机构的偏好?i、 e.共享锁优于升级锁问题在于,当另一个读写器抓取互斥锁时,读写器都无法轻松克服紧密循环。看看你的要点: 锁互斥 睡眠 释放互斥 转到步骤1 第3步之后的窗口是读写器获取互斥锁的唯一机会。这个窗口很短,所以它抓住它的机会很小。这就是为什么您只能看到写入程序或读卡器打印到控制台。事实上,如果你永远等待,你很可能会看到不同的实体将获得工作的机会 那么如何修复它呢?这很简单:只需将睡眠从锁中移出,如下所示:
是否有锁定机构的偏好?i、 e.
共享锁
优于升级锁
问题在于,当另一个读写器抓取互斥锁时,读写器都无法轻松克服紧密循环。看看你的要点:
writerreader0started
reader3startedreader
0: Got the lock
0reader2reader3: Got the lock
reader1started
reader1: Got the lock
started
started
reader2: Got the lock
reader0: Got the lock
reader3: Got the lock
reader1: Got the lock
reader2: Got the lock
reader1: Got the lock
reader2: Got the lock
reader0: Got the lock
reader3: Got the lock
readerreader3: Got the lock
reader2: Got the lock
0: Got the lock
void编写器(int-id)
{
cerr“问题是,一旦编写器拥有互斥体或读卡器拥有互斥体,owernership就不会转移到它的相反线程(readers->writer/writer->readers)”这难道不是互斥体的全部用途吗(互斥)同步机制是关于??你的意思是实现一个吗?我想这已经可以从当前的c+标准BTW中获得。不需要使用boost。
writer0started
readerwriterreader0: Got the lock
readerreader21started30started
started
started
writer0: Got the lock
writer0: Got the lock
writer0: Got the lock
writer0: Got the lock
writer0: Got the lock
writerreader0started
reader3startedreader
0: Got the lock
0reader2reader3: Got the lock
reader1started
reader1: Got the lock
started
started
reader2: Got the lock
reader0: Got the lock
reader3: Got the lock
reader1: Got the lock
reader2: Got the lock
reader1: Got the lock
reader2: Got the lock
reader0: Got the lock
reader3: Got the lock
readerreader3: Got the lock
reader2: Got the lock
0: Got the lock
void writer(int id)
{
cerr << "writer" << id << "started" << endl;
while(gSignalStatus) {
{
boost::upgrade_lock<boost::shared_mutex> lock(g_mutex);
boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(lock);
cout << "writer" << id << ": Got the lock" << endl;
}
boost::this_thread::sleep(boost::posix_time::milliseconds(200));
}
}
void reader(int id)
{
cerr << "reader" << id << "started" << endl;
while(gSignalStatus) {
{
boost::shared_lock<boost::shared_mutex> lock(g_mutex);
cerr << "reader" << id << ": Got the lock" << endl;
}
boost::this_thread::sleep(boost::posix_time::milliseconds(200));
}
}