【发布时间】:2014-02-05 19:01:20
【问题描述】:
我正在尝试实现一个屏障函数,这样当一个线程调用waitBarrier() 时,它会等到所有其他n 线程都调用了该函数,之后一切都会继续,即一种同步构造。
我有以下代码:
int i = 0; // Shared variable. Initialized as 0 at the beginning.
waitBarrier() {
// CAS = Compare-and-swap, the first argument holds "old_val" the second the new
i = CAS(i, i+1);
// Spin until all n threads (number of all threads known prior) have been "here"
while (i != n) {}
}
如果被n 线程访问,这个函数会起作用吗?原子函数返回值的赋值是原子的吗?还是会出现竞争条件?
【问题讨论】:
-
如果它工作,它会工作很糟糕,(自旋锁)。
-
好吧,假设所有线程都等待很短的时间,它应该是相当有效的。
-
等待的线程越多,留给其他线程的 CPU 和内存带宽就越少。
标签: multithreading locking race-condition spinlock compare-and-swap