我正在阅读有关障碍的信息,在 Wikipedia 中找到了一个示例。我怀疑它是否正确。这是来自(https://en.wikipedia.org/wiki/Barrier_(computer_science)#Implementation)的代码
struct barrier_type
{
// how many processors have entered the barrier
// initialize to 0
int arrive_counter;
// how many processors have exited the barrier
// initialize to P
int leave_counter;
int flag;
std::mutex lock;
};
// barrier for p processors
void barrier(barrier_type* b, int p)
{
b->lock.lock();
if (b->leave_counter == P)
{
if (b->arrive_counter == 0) // no other threads in barrier
{
b->flag = 0; // first arriver clears flag
}
else
{
b->lock.unlock();
while (b->leave_counter != P); // wait for all to leave before clearing
b->lock.lock();
b->flag = 0; // first arriver clears flag
}
}
b->arrive_counter++;
int arrived = b->arrive_counter;
b->lock.unlock();
if (arrived == p) // last arriver sets flag
{
b->arrive_counter = 0;
b->leave_counter = 1;
b->flag = 1;
}
else
{
while (b->flag == 0); // wait for flag
b->lock.lock();
b->leave_counter++;
b->lock.unlock();
}
}
在barrier函数中,在进入第一个if
block之前,先leave_counter
比较P
是否等于P
。再次在else
块中,有一个比较。
第二次比较的原因是什么,因为控件仅在leave_counter
值为时输入P
?我在这里错过了什么吗?