【编程】linux多线程同步机制——屏障

复习:

线程同步方式:互斥量读写锁条件变量自旋锁屏障

屏障(barrier)是用户协调多个线程并行工作的同步机制。屏障允许每个线程等待,直到所有合作线程都到达某一点,然后从该点继续执行。

int pthread_barrier_init(pthread_barrier_t *restrict barrier, const pthread_barrierattr_t * restrict attr, unsigned int count);
int pthread_barrier_destory(pthread_barrier_t * barrier);
int pthread_barrier_wait(pthread_barrier_t *barrier)
#include 
#include 
#include 
#include 
#include 

#define NTHR 8
#define NUMMUM 8000000L
#define TNUM (NUMMUM/NTHR)

long nums[NUMMUM];
long snums[NUMMUM];

pthread_barrier_t b;

#ifdef SOLARIS
#define heapsort qsort
#else
extern int heapsort(void *,size_t, size_t,int(*)(const void*,const void*));
#endif

int complong(const void *arg1, const void *arg2)
{
	long l1=*(long*)arg1;
	long l2=*(long*)arg2;

	if(l1=l2)
		return 0;
	else if (l1<l2)
		return -1;
	else
		return 1;
}

void * thr_fn(void*arg)
{
	long idx=(long)arg;

	heapsort(&nums[idx], TNUM, sizeof(long), complong);
	pthread_barrier_wait(&b);
	return ((void*)0);
}


void merge()
{
	long idx[NTHR];
	long i,minidx,sidx,num;

	for(i = 0; i < NTHR; i++)
	{
		idx[i] = i * TNUM;
	}

	for (sidx = 0; sidx < NUMMUM; sidx++)
	{
		num = LONG_MAX;
		for (i=0; i < NTHR; i++)
		{
			if ((idx[i] < (i+1)*TNUM) && (nums[idx[i]] < num)) {
				num = nums[idx[i]];
				minidx = i;
			}
			snums[sidx] = nums[idx[minidx]];
			idx[minidx]++;
		}
	}
}


int main(int argc, char *argv[])
{
	unsigned long i;
	struct timeval start,end;
	long long startusec, endusec;
	double elapsed;
	int err;
	pthread_t tid;

	srandom(1);
	for (i=0; i < NUMMUM; i++)
	{
		nums[i] = random();
	}

	gettimeofday(&start, NULL);
	pthread_barrier_init(&b, NULL, NTHR+1);
	for(i = 0; i < NTHR; i++)
	{
		err = pthread_create(&tid, NULL, thr_fn, (void*)(i*TNUM));
		if (err != 0)
		{
			printf("can't create\n");
		}
	}
	pthread_barrier_wait(&b);
	merge();
	gettimeofday(&end, NULL);

	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);

	for (i = 0; i < NUMMUM; i++)
	{
		printf("%ld\n",snums[i]);
	}

	return 0;
}




你可能感兴趣的:(linux,c,编程,linux,c)