我的程序是死锁的,我不知道为什么,因为当我在调试器中运行它时它不会这样做,所以我的第一个怀疑是我的rwLock,我写了我自己的版本因为我只想使用标准库 - 我认为在C ++ 17之前不包含rwLock - 这不是我通常做的事情。
class RwLock
{
std::mutex mutex;
std::unique_lock<std::mutex> unique_lock;
std::condition_variable condition;
int reading_threads;
bool writing_threads;
public:
RwLock();
~RwLock();
void read_lock();
void read_unlock();
void write_lock();
void write_unlock();
};
RwLock::RwLock() :
mutex(),
unique_lock(mutex, std::defer_lock),
condition(),
reading_threads(0),
writing_threads(false)
{
}
RwLock::~RwLock()
{
//TODO: find something smarter to do here.
write_lock();
}
void RwLock::read_lock()
{
unique_lock.lock();
while(writing_threads)
{
condition.wait(unique_lock);
}
++reading_threads;
unique_lock.unlock();
}
void RwLock::read_unlock()
{
unique_lock.lock();
if(--reading_threads == 0)
{
condition.notify_all();
}
unique_lock.unlock();
}
void RwLock::write_lock()
{
unique_lock.lock();
while(writing_threads)
{
condition.wait(unique_lock);
}
writing_threads = 1;
while(reading_threads)
{
condition.notify_all();
}
unique_lock.unlock();
}
void RwLock::write_unlock()
{
unique_lock.lock();
writing_threads = 0;
condition.notify_all();
unique_lock.unlock();
}
答案 0 :(得分:0)
std::shared_timed_mutex
存在于C ++ 17之前:在C ++ 14中。
使用它,它会有更少的错误,几乎可以肯定更快。
C ++ 17引入了shared_mutex
,它可以更快。但我强烈怀疑你能否使用C ++标准原语实现比shared_timed_mutex
更快的共享rwlock。
答案 1 :(得分:0)
除了此代码中的两个问题外,看起来不错:
void RwLock::write_lock()
{
unique_lock.lock();
while(writing_threads)
{
condition.wait(unique_lock);
}
writing_threads = 1;
while(reading_threads)
{
condition.notify_all();
}
unique_lock.unlock();
}
首先,你加快writing_threads
。读者可以潜入。可能你不介意甚至想要这个,但通常这是不受欢迎的。
其次,您在上一个while
循环中的通知应为wait
。把它放在一起,我们得到:
void RwLock::write_lock()
{
unique_lock.lock();
++writing_threads;
while((writing_threads > 1) || (reading_threads > 0))
{
condition.wait(unique_lock);
}
unique_lock.unlock();
}
void RwLock::write_unlock()
{
unique_lock.lock();
--writing_threads; // note change here
condition.notify_all();
unique_lock.unlock();
}
这实际上有点简单,这很好。