void processCachedData() {
rwl.readLock().lock();
if (!cacheValid) {
// Must release read lock before acquiring write lock
5: rwl.readLock().unlock();
6: rwl.writeLock().lock();
// Recheck state because another thread might have acquired
// write lock and changed state before we did.
if (!cacheValid) {
data = ...
cacheValid = true;
}
// Downgrade by acquiring read lock before releasing write lock
14: rwl.readLock().lock();
15: rwl.writeLock().unlock(); // Unlock write, still hold read
}
use(data);
rwl.readLock().unlock();
}
? 현재 스레드가 읽기 잠금을 보유하고 있으면 현재 스레드가 읽기 잠금을 보유하고 있는지 여부에 관계없이 다른 스레드가 더 이상 읽지 않을 때 쓰기 잠금을 획득 할 수 있어야합니다. 이것은 내가 기대하는 행동입니다. 결국 4 번과 5 번 라인에서 업그레이드를 잠그고 14 번과 15 번 라인에서 다운 그레이드하면 ReentrantReadAndWriteLock 클래스에서 내부적으로 완료 될 것으로 예상됩니다. 왜 그럴 수 없습니까?
은 즉, 나는 코드는 다음과 같이 잘 작동하는 기대 :
void processCachedData() {
rwl.readLock().lock();
if (!cacheValid) {
// The readlock is upgraded to writeLock when other threads
// release their readlocks.
rwl.writeLock().lock();
// no need to recheck: other threads can't have acquired
// the write lock since this thread still holds also the readLock!!!
if (!cacheValid) {
data = ...
cacheValid = true;
}
// Downgrade by acquiring read lock before releasing write lock
rwl.writeLock().unlock(); // Unlock write, still hold read
}
use(data);
rwl.readLock().unlock();
}
이가, 더 잠금 처리 할 수있는보다 안전한 방법으로 많이하지 않습니다 보인다?
누군가가 왜이 이상한 구현을 설명 할 수 있습니까? 감사.
두 개 이상의 스레드가 동시에이 작업을 수행하려고하면 어떤 일이 발생할지 고려해야합니다. – EJP