这个函数为什么永远不会终止?

huangapple go评论65阅读模式
英文:

Why does this function never terminate?

问题

以下是要翻译的内容:

为什么以下函数会出现死锁?换句话说,为什么它阻止任何人获得读锁和写锁?难道读锁不能被共享?

	void testReadWriteLock() throws InterruptedException {
		final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

		// 其他线程获取读锁并永不释放它。
		new Thread(() -> lock.readLock().lock()).start();
		Thread.sleep(100);

		// 其他线程尝试(并失败)获取写锁。
		new Thread(() -> lock.writeLock().lock()).start();
		Thread.sleep(100);

		lock.readLock().lock(); // 这会永远阻塞
	}
英文:

Why does the following function deadlock? In other words, why does it prevent anyone from obtaining, not only the write lock, but the read lock? Can't read locks be shared?

	void testReadWriteLock() throws InterruptedException {
		final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

		// Other thread acquires read lock and never releases it.
		new Thread(() -> lock.readLock().lock()).start();
		Thread.sleep(100);

		// Other thread attempts (and fails) to acquire write lock.
		new Thread(() -> lock.writeLock().lock()).start();
		Thread.sleep(100);

		lock.readLock().lock(); // This blocks forever
	}

答案1

得分: 0

我发现了ReentrantReadWriteLock的一个有趣特性:任何尝试获取写锁(即使是阻塞的)都会阻止所有后续尝试获取读锁的操作(除非是可重入尝试)。至少在Oracle的1.8 JVM中是这样的情况。优先考虑写入操作确实有一定的逻辑:它确保数据是最新的。

英文:

I discovered an interesting property of ReentrantReadWriteLock: any attempt to acquire the write lock (even blocking) blocks all subsequent attempts to acquire read locks (except re-entrant attempts). At least, that's the case in Oracle's 1.8 JVM. There is a certain logic in prioritizing writes: it ensures that data is up-to-date.

答案2

得分: 0

你可以让多个线程获取读锁,但当获取写锁时,其他所有线程都会被阻塞。由于你从未解锁任何内容,方法中的最后一次锁定调用将永远无法获取锁。

英文:

You can have multiple threads obtain the read lock, but when the write lock is obtained, everyone else is blocked out. Since you never unlock anything, the final lock call in the method will never obtain the lock.

huangapple
  • 本文由 发表于 2020年8月14日 03:32:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63402076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定