屏障是多线程同步的一种方法。barrier意为屏障或者栏杆,把先后到达的多个线程挡在同一栏杆前,直到所有线程到齐,然后撤下栏杆同时放行。先到达的线程将会阻塞,等到所有调用pthread_barrier_wait()函数的线程(数量等于屏障初始化时指定的count)都到达后,这些线程才会由阻塞状态进入就绪状态再次参与系统调度。屏障是基于条件变量和互斥锁实现的。主要操作包括:调用pthread_barrier_init()初始化一个屏障,其他线程调用pthread_barrier_wait(),所有线程到期后线程唤醒进入准备状态,屏障不在使用调用pthread_barrier_destroy()销毁一个屏障
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
/* 线程控制块 */
static pthread_t tid1;
static pthread_t tid2;
static pthread_t tid3;
/* 屏障控制块 */
static pthread_barrier_t barrier;
/* 函数返回值检查函数 */
static void check_result(char* str,int result)
{
if (0 == result)
{
printf("%s successfully!\n",str);
}
else
{
printf("%s failed! error code is %d\n",str,result);
}
}
/*线程1入口函数*/
static void* thread1_entry(void* parameter)
{
int count = 0;
printf("thread1 have arrived the barrier!\n");
pthread_barrier_wait(&barrier); /* 到达屏障,并等待其他线程到达 */
while (1)
{
/* 打印线程计数值输出 */
printf("thread1 count: %d\n",count ++);
/* 休眠2秒*/
sleep(2);
}
}
/*线程2入口函数*/
static void* thread2_entry(void* parameter)
{
int count = 0;
printf("thread2 have arrived the barrier!\n");
pthread_barrier_wait(&barrier);
while (1)
{
/* 打印线程计数值输出 */
printf("thread2 count: %d\n",count ++);
/* 休眠2秒*/
sleep(2);
}
}
/* 线程3入口函数 */
static void* thread3_entry(void* parameter)
{
int count = 0;
printf("thread3 have arrived the barrier!\n");
pthread_barrier_wait(&barrier);
while (1)
{
/* 打印线程计数值输出 */
printf("thread3 count: %d\n",count ++);
/* 休眠2秒*/
sleep(2);
}
}
/* 用户应用入口 */
int application_init()
{
int result;
pthread_barrier_init(&barrier,NULL,3);
/*创建线程1,线程入口是thread1_entry, 属性参数设为NULL选择默认值,入口参数为NULL*/
result = pthread_create(&tid1,NULL,thread1_entry,NULL);
check_result("thread1 created",result);
/*创建线程2,线程入口是thread2_entry, 属性参数设为NULL选择默认值,入口参数为NULL*/
result = pthread_create(&tid2,NULL,thread2_entry,NULL);
check_result("thread2 created",result);
/*创建线程3,线程入口是thread3_entry, 属性参数设为NULL选择默认值,入口参数为NULL*/
result = pthread_create(&tid3,NULL,thread3_entry,NULL);
check_result("thread3 created",result);
return 0;
}
int main()
{
int i ;
application_init();
i=100;
do{
sleep(1);
}while(i--);
}
运行结果:
-bash-3.2$ gcc -pthread barrier.c -o 8app
-bash-3.2$ ./8app
thread1 created successfully!
thread2 created successfully!
thread3 created successfully!
thread1 have arrived the barrier!
thread2 have arrived the barrier!
thread3 have arrived the barrier!
thread1 count: 0
thread2 count: 0
thread3 count: 0
thread1 count: 1
thread2 count: 1
thread3 count: 1
thread1 count: 2
thread2 count: 2
thread3 count: 2
thread2 count: 3
thread3 count: 3
thread1 count: 3
thread2 count: 4
thread3 count: 4
thread1 count: 4
thread2 count: 5
thread3 count: 5
thread1 count: 5
thread2 count: 6
thread3 count: 6
thread1 count: 6
thread2 count: 7
thread3 count: 7
thread1 count: 7
thread2 count: 8
thread3 count: 8
thread1 count: 8
thread2 count: 9
thread3 count: 9
thread1 count: 9