java - 了解 ReusableBarrier 问题(来自 'Little Book of Semaphores' )

标签 java concurrency

问题描述如下:

通常,一组协作线程会循环执行一系列步骤,并且 每个步骤后在屏障处同步。对于这个应用程序,我们需要一个可重复使用的 当所有线程都通过后,屏障会锁定自身。

给出的解决方案是:

1 # rendezvous
2
3 mutex.wait()
4     count += 1
5     if count == n:
6         turnstile2.wait() # lock the second
7         turnstile.signal() # unlock the first
8 mutex.signal()
9
10 turnstile.wait() # first turnstile
11 turnstile.signal()
12
13 # critical point
14
15 mutex.wait()
16     count -= 1
17     if count == 0:
18         turnstile.wait() # lock the first
19         turnstile2.signal() # unlock the second
20 mutex.signal()
21
22 turnstile2.wait() # second turnstile
23 turnstile2.signal()

假设我们将此屏障用于 2 个线程,并通过此屏障泵送 100 个线程。当第二个线程解锁 Turnstile(7) 并到达第 9 行时,现在,线程 3 出现,
它增加计数,
count > n 因此它释放互斥体,
由于十字转门已解锁,因此也达到了临界点,
同样,线程4、线程5、线程6可以执行临界点,执行次数超过2次。
是什么阻止他们在线程 2 之前通过屏障?还是我的理解有误?

最佳答案

问题陈述指出(第 22 页):

You can assume that there are n threads and that this value is stored in a variable, n, that is accessible from all threads.

因此,如果 n=2 并且有 100 个线程,则违反了此假设,并且该解决方案将不起作用。

关于java - 了解 ReusableBarrier 问题(来自 'Little Book of Semaphores' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5925204/

相关文章:

java - 获取方法中局部变量的数量

java - 构建具有不同列数的 html 表

java - 每小时英里计算器

mysql插入如果不存在,并发 session

java - 即使线程终止后锁也不会释放

java - Java内存模型中局部最终变量的语义?

java - android java从XML调用按钮而不获取NULL

java - 多个 Applet - stop() 和 destroy()

go - 我怎样才能生成依赖于它们的前辈的例程?

java - 如何使多个线程中的一个线程运行最长时间(等待队列中的最短时间)?