LINUX之屏障
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #define PTHREAD_BARRIER_SIZE 4 pthread_barrier_t barrier; void err_exit(const char *err_msg) { printf("error:%s\n", err_msg); exit(1); } void *thread_fun(void *arg) { int result; char *thr_name = (char *)arg; printf("线程%s工作完成...\n", thr_name); result = pthread_barrier_wait(&barrier); if (result == PTHREAD_BARRIER_SERIAL_THREAD) printf("线程%s,wait后第一个返回\n", thr_name); else if (result == 0) printf("线程%s,wait后返回为0\n", thr_name); return NULL; } int main(void) { pthread_t tid_1, tid_2, tid_3; /* 初始化屏障 */ pthread_barrier_init(&barrier, NULL, 3); if (pthread_create(&tid_1, NULL, thread_fun, "1") != 0) err_exit("create thread 1"); if (pthread_create(&tid_2, NULL, thread_fun, "2") != 0) err_exit("create thread 2"); if (pthread_create(&tid_3, NULL, thread_fun, "3") != 0) err_exit("create thread 3"); /* 主线程等待工作完成 */ pthread_barrier_wait(&barrier); printf("所有线程工作已完成...\n"); printf("%d ...\n",_POSIX_THREADS); sleep(1); return 0; }
/* 程序功能: 创建一个动态数组,给数组赋初值,创建NUM_THREAD个线程,为长度为SIZE的数组初始化,通过(线程屏障同步) 当所有线程处理完后则打印整个数组的值。通过时间计数来比较所花费的时间。 当采用8个线程时花费sort took 0.0958 seconds 当采用四个线程时 thread -1249961072 done job. thread -1260450928 done job. thread -1239471216 done job. thread -1270944880 done job. sort took 0.1104 seconds 当采用一个线程时 thread -1239983216 done job. sort took 0.2567 seconds */ #include <pthread.h> #include <stdlib.h> #include <stdio.h> #define SIZE 8000000L //数组长度 #define NUM_THREAD 8 //线程个数 #define SIZE_PER (SIZE/NUM_THREAD)//每个线程要处理的数组长度 pthread_barrier_t barrier;//定义屏障 int *a; /*每个线程的线程处理函数*/ void * thr_fun(void *arg) { long n = (long)arg; long i; for(i=n;i<n+SIZE_PER;i++) { a[i] = i; } printf("thread %d done job.\n",pthread_self()); int result=pthread_barrier_wait(&barrier); //阻塞等待直到主线程满足了屏障计数 if (result == PTHREAD_BARRIER_SERIAL_THREAD) printf("线程%d,wait后第一个返回\n", arg); else if (result == 0) printf("线程%d,wait后返回为0\n", arg); return ((void *)1); } int main() { pthread_t tid; struct timeval start,end; long long startusec,endusec; double elapsed; int i; a = (int *)malloc(SIZE*sizeof(int)); //动态分配数组 pthread_barrier_init(&barrier,NULL,5+1);//初始化线程屏障计数为子线程个数加上主线程 gettimeofday(&start,NULL);//获得起始时间 for(i=0;i<NUM_THREAD;i++) { pthread_create(&tid,NULL,thr_fun,(void *)(i*SIZE_PER));//创建子线程 } pthread_barrier_wait(&barrier);//等待所有子线程处理完成 gettimeofday(&end,NULL);//获得结束时间 for(i=0;i<SIZE;i++)//打印数组内容 //printf("%d ",a[i]); startusec = start.tv_sec * 1000000 + start.tv_usec; endusec = end.tv_sec * 1000000 + end.tv_usec; elapsed = (double)(endusec-startusec)/1000000.0;//计算处理所花费的时间 printf("sort took %.4f seconds\n",elapsed); return 0; }