Java - 实现忙等待机制 [英] Java - implementing a busy wait mechanism
问题描述
在我的项目中,到目前为止,我使用 Runnable)6/docs/api/java/util/concurrent/CyclicBarrier.html" rel="nofollow">CyclicBarrier
.就我而言,由于同步频率高,使用 CyclicBarrier
效率低下,但忙等待机制可能工作得更快.这是我到目前为止得到的(有些部分被遗漏了):
in my project I have until now "synchronized" multiple threads (each running the same type of Runnable
) using a CyclicBarrier
. In my case, using a CyclicBarrier
turned out to be inefficient due to the high frequency of synchronizations, but a busy-wait mechanism might work faster. Here's what I got so far (some parts left out):
public class MyRunnable implements Runnable {
private static AtomicInteger counter = null; // initialized to the number
// of threads
public void run() {
// do work up to a "common point"
synchronized (this) {
// decrement the counter and - if necessary - reset it
if (counter.decrementAndGet() == 0) {
counter.set(numberOfThreads);
// make all the busy waiting threads exit from the loop
for (int i = 0; i < threads.length; i++)
threads[i].interrupt();
}
}
// busy wait until all threads have reached the "common point"
while (!Thread.interrupted()) {}
}
}
不幸的是,此代码的性能甚至比 CyclicBarrier
还要差.这是一个简短的可编译示例.关于如何改进它的任何建议?
Unfortunately, this code performs even worse than CyclicBarrier
. Here's a short, compilable example. Any suggestions on how to improve it?
推荐答案
如果处理器数量多于线程正在运行,这里的忙碌等待只会更快"地工作.如果您不断旋转 Thread.interrupted 并且只是消耗 CPU 时间,您实际上会显着降低性能.
Busy wait here will only work 'faster' if you have more processors then you have threads running. If you continuously spin on Thread.interrupted and are just consuming CPU time you will actually degrade performance dramatically.
CyclicBarrier/CountDownLatch 出了什么问题?这似乎是一个更好的解决方案.
What went wrong with a CyclicBarrier/CountDownLatch? That seems like a much better solution.
这篇关于Java - 实现忙等待机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!