一旦作家在Reader writer锁定中完成写入,Reader就不会醒来

时间:2015-05-28 19:13:58

标签: c++ multithreading mutex deadlock condition-variable

class ReadLock
{
private:
    std::mutex readWriteMutex;
    std::mutex conditionmtx;
    std::condition_variable cv;
    int readings = 0;
    int writings = 0;
    int writers = 0;
public:
    void AquireReadLock()
    {
        readWriteMutex.lock();
        if (writers)
        {
            std::unique_lock<std::mutex> lck(conditionmtx);
            cv.wait(lck);
        }
        while (writings)
        {
            std::unique_lock<std::mutex> lck(conditionmtx);
            cv.wait(lck);
        }
        readings++;
        readWriteMutex.unlock();
    }
    void ReleaseReadLock()
    {
        readWriteMutex.lock();
        //std::unique_lock<std::mutex> lck(conditionmtx);
        cv.notify_all();
        readings--;
        readWriteMutex.unlock();
    }
    void  AquireWriteLock()
    {
        readWriteMutex.lock();
        writers++;
        while (readings || writings)
        {
            std::unique_lock<std::mutex> lck(conditionmtx);
            cv.wait(lck);
        }
        writings++;
        readWriteMutex.unlock();
    }
    void ReleaseWriteLock()
    {
        readWriteMutex.lock();
        writings--;
        writers--;;
        //std::unique_lock<std::mutex> lck(conditionmtx);
        cv.notify_all();
        readWriteMutex.unlock();
    }

};

ReadLock lock;
void WriteFunction(int id)
{
    std::cout << "thread " + std::to_string(id) + " asks for write " << '\n';
    lock.AquireWriteLock();
    std::cout << "thread " + std::to_string(id) + " writting" << '\n';
    std::this_thread::sleep_for(std::chrono::milliseconds(3500));
    std::cout << "thread " + std::to_string(id) + " finished writting" << '\n';
    lock.ReleaseWriteLock();
}
void ReadFunction(int id)
{
    if (id == 0)
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    std::cout << "thread " + std::to_string(id) + " asks for read" << '\n';
    lock.AquireReadLock();
    std::cout << "thread " + std::to_string(id) + " reading" << '\n';
    std::this_thread::sleep_for(std::chrono::milliseconds(2500));
    std::cout << "thread " + std::to_string(id) + " finished reading" << '\n';
    lock.ReleaseReadLock();
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::thread threads[3];

    for (int i = 0; i < 3; ++i)
    if (i % 2 == 0)
        threads[i] = std::thread(ReadFunction, i);
    else
        threads[i] = std::thread(WriteFunction, i);

    for (auto& th : threads) th.join();

}

我正在尝试使用条件变量和Mutex实现读写器锁。线程2首先写入,线程0和线程1等待线程2完成写入但是一旦线程2完成写入线程1并且线程0没有唤醒读取。有人帮我解决这个问题?我是c ++同步的新手

1 个答案:

答案 0 :(得分:3)

此代码会在writerRelease()readerRealease() debending上产生死锁,这是一个问题。

如何查找?

多线程代码很难调试。我建议你在这里添加一些日志记录,以便在输入aquire / release函数时以及互斥锁被锁定时显示。

例如:

void ReleaseReadLock()
{
    cout <<this_thread::get_id()<< " will release ReadLock" << endl;
    readWriteMutex.lock();
    cout << this_thread::get_id() << " ...mutex locked" << endl;
    cv.notify_all();
    cout << this_thread::get_id() << " ...notified" << endl;
    readings--;
    readWriteMutex.unlock();
    cout << this_thread::get_id()<<" released ReadLock " << endl;
}

使用此类代码,您将观察到这种情况(或其略微变体):

5204 thread 1 asks for write
3692 thread 2 asks for read
5204 will aquire WriteLock   ==> start write lock acquisition 
3692 will aquire ReadLock    ==> start read lock acquisition  
3692 ...mutex locked         ==> mutex was locked for read lock  acquisition
3692 aquired ReadLock        ==> mutex was unlocked : end read lock acquisition. 
5204 ...mutex locked         ==> mutext was locked for writelock 
3692 thread 2 reading        
5288 thread 0 asks for read
5288 will aquire ReadLock    ==> another read lock will wait for mutex
3692 thread 2 finished reading
3692 will release ReadLock   ==> Reader can't release lock because mutex is locked by writelock

会发生什么?

释放锁是成功获得的。所以 readings 是1。

要减少此变量,releaseReadLock()必须终止其作业。但它不能,因为它在函数开头需要的互斥量仍然由aquireWriteLock()保持。所以它等待。

aquireWriteLock()卡在一个循环中,只要 readings 或着作,它就会继续循环。它将释放只有readings的互斥锁返回到0.

简而言之,releaseReadLock()acquireWriteLock()都被卡住了,等待着彼此。

如何解决?

好吧,死锁是一件非常讨厌的事情。

helsp的一个方面是始终以相同的顺序对多个对象执行锁定。然后一个人可能会偶然失败锁定,但是没有&#34;死亡之吻&#34;。

更具体地说,查看您的代码,我的印象是您的readWriteMutex主要是为了防止您的3个柜台上的竞争条件。我建议摆脱这个互斥量并改用原子变量。

然后在ReleaseReadLock()中,您应该在通知等待线程之前减少读取器的数量。有了这两个措施,我可以运行几次没有死锁(这并不能证明它是完美的,但至少可以避免最明显的情况。由你来详细分析/验证)。

class ReadLock
{
private:
    std::mutex conditionmtx;
    std::condition_variable cv;
    atomic<int> readings = 0;   // atomics don't need mutex for being updated
    atomic<int> writings = 0;
    atomic<int> writers = 0;
public:
    void AquireReadLock()
    {
        cout << this_thread::get_id() << " will aquire ReadLock" << endl;
        if(writers) {
            std::unique_lock<std::mutex> lck(conditionmtx);
            cv.wait(lck);
        }
        while(writings) {
            std::unique_lock<std::mutex> lck(conditionmtx);
            cv.wait(lck);
        }
        readings++;
        cout << this_thread::get_id() << " aquired ReadLock" << endl;
    }
    void ReleaseReadLock()
    {
        cout <<this_thread::get_id()<< " will release ReadLock" << endl;
        readings--;
        cv.notify_all();
        cout << this_thread::get_id()<<" released ReadLock " << endl;
    }
    void  AquireWriteLock()
    {
        cout << this_thread::get_id() << " will aquire WriteLock" << endl;
        writers++;
        while(readings || writings) {
            std::unique_lock<std::mutex> lck(conditionmtx);
            cv.wait(lck);
        }
        writings++;
        cout << this_thread::get_id() << " aquired  WriteLock" << endl;
    }
    void ReleaseWriteLock()
    {
        cout << this_thread::get_id() << " will release WriteLock" << endl;
        writings--;
        writers--;;
        cv.notify_all();
        cout << this_thread::get_id() << " ...notified" << endl;
        cout << this_thread::get_id() << " released WriteLock" << endl;
    }
};