线程屏障是线程同步的一种方式. 线程执行操作后,可能需要等待其他线程完成操作. 这时,当前线程将被挂起,直到另一个线程也完成一个操作,最后所有线程都被唤醒. 屏障具有三个主要功能.
int
pthread_barrier_wait(pthread_barrier_t *barrier)
{
pthread_descr self = thread_self();
pthread_descr temp_wake_queue, th;
int result = 0;
__pthread_lock(&barrier->__ba_lock, self);
/* If the required number of threads have achieved rendezvous... */
// pthread_barrier_wait被调用的次数达到阈值,__ba_present + 1 == __ba_required
if (barrier->__ba_present >= barrier->__ba_required - 1)
{
/* ... then this last caller shall be the serial thread */
result = PTHREAD_BARRIER_SERIAL_THREAD;
/* Copy and clear wait queue and reset barrier. */
// 被阻塞的线程队列
temp_wake_queue = barrier->__ba_waiting;
// 重置字段
barrier->__ba_waiting = NULL;
barrier->__ba_present = 0;
}
else
{
result = 0;
// 执行pthread_barrier_wait一次,加一
barrier->__ba_present++;
// 插入等待队列
enqueue(&barrier->__ba_waiting, self);
}
__pthread_unlock(&barrier->__ba_lock);
// 调用pthread_barrier_wait的次数还不够
if (result == 0)
{
/* Non-serial threads have to suspend */
// 挂起当前线程
suspend(self);
/* We dont bother dealing with cancellation because the POSIX
spec for barriers doesnt mention that pthread_barrier_wait
is a cancellation point. */
}
else
{
/* Serial thread wakes up all others. */
// 唤醒其他的线程
while ((th = dequeue(&temp_wake_queue)) != NULL)
restart(th);
}
return result;
}
int
pthread_barrier_init(pthread_barrier_t *barrier,
const pthread_barrierattr_t *attr,
unsigned int count)
{
if (count == 0)
return EINVAL;
__pthread_init_lock(&barrier->__ba_lock);
// 需要执行pthread_barrier_wait的次数
barrier->__ba_required = count;
// 已经调用pthread_barrier_wait的次数
barrier->__ba_present = 0;
// 调用pthread_barrier_wait被阻塞的线程队列
barrier->__ba_waiting = NULL;
return 0;
}
int
pthread_barrier_destroy(pthread_barrier_t *barrier)
{
// 有线程在等待
if (barrier->__ba_waiting != NULL) return EBUSY;
return 0;
}
从代码中我们知道,障碍的本质是计数. 当尚未达到一定数量时pthread 线程挂起,当前线程被阻止. 当最后一个线程执行pthread_barrier_wait函数并获得一定数目时pthread 线程挂起,所有线程都被唤醒.
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-210690-1.html