本文介绍了如何使用ReentrantReadWriteLock等待数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据说, ReentrantReadWriteLock 适用于一位作家和多位读者。

It is said, that ReentrantReadWriteLock is intended for one writer and multiple readers.

尽管如此,读者应该等到缓冲区中存在一些数据。

Nevertheless, readers should wait until some data is present in the buffer.

那么,要锁定什么?

我创建了如下的并发对象:

I created concurrency objects like follows:

private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
protected final Lock readLock = rwl.readLock();
protected final Lock writeLock = rwl.writeLock();
protected final Condition hasData = writeLock.newCondition();

现在写入方法我做:

writeLock.lock();

// writing first portion and updating variables

hasData.signalAll();

// if required then writing second portion and updating variables

hasData.signalAll();

但如何写一个读者?它应该只获得 readLock 吗?但它如何等待信号呢?如果它还获得 writeLock 那么读/写锁定的优势在哪里?

But how to write a reader? Should it acquire only readLock? But how it can wait for a signal then? If it aquires also a writeLock then where is the supremacy fo read/write locking?

如果只有 writeLock 受保护,如何确保所需变量在读取时不会改变?

How to ensure required variables will not change during reading if they are protected only by writeLock?

队列号与任务不匹配

这是关于 ReentrantReadWriteLock 。

推荐答案

ReentrantReadWriteLock确实有点混乱,因为readLock没有没有条件。
您必须升级到阅读器中的writeLock才能等待条件。

The ReentrantReadWriteLock is indeed a bit confusing because the readLock doesn't have a condition.You have to upgrade to a writeLock in your reader only to wait for the condition.

在作者中。

writeLock.lock(); //locks all readers and writers
// do write data
hasData.signalAll();
writeLock.unlock();

在读者中你可以:

readLock.lock(); //blocks writers only
try{
 if(!checkData()) //check if there's data, don't modify shared variables
 {
  readLock.unlock();
  writeLock.lock(); // need to lock the writeLock to allow to use the condition.
                    // only one reader will get the lock, other readers will wait here
  try{
   while(!checkData()) // check if there' still no data
   {
     hasData.await(); //will unlock and re-lock after writer has signalled and unlocked.
   }
   readLock.lock();    // continue blocking writer
  }
  finally
  {
    writeLock.unlock(); //let other readers in
  }
 }
 //there should be data now
 readData(); // don't modify variables shared by readers.
}
finally
{
  readlock.unlock(); //let writers in
}

为了完整性,每个unlock()应该在一个当然,终于阻止了。

For completeness, each unlock() should be in a finally block, of course.

这篇关于如何使用ReentrantReadWriteLock等待数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:18
查看更多