我正在尝试实现一个屏障函数,这样当一个线程调用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
线程访问,这个函数会起作用吗?原子函数返回值的赋值是原子的吗?或者可能会出现竞争条件?