티스토리 뷰
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "timers.h"
#include <time.h>
#define RANGE 100
#define MAX_NUM 1000
void *worker(void *);
typedef struct
{
int tid;
int thread_num;
int *data;
int **buckets;
pthread_barrier_t *barrier;
} thread_args;
int main(int argc, char** argv)
{
int thread_num=0;
int i, j;
thread_args arg[MAX_NUM];
int *buckets[MAX_NUM];
int data[MAX_NUM];
if(argc < 2)
{
printf("please input number\n");
return 0;
}
thread_num = atoi(argv[1]);
if(thread_num < 1 || thread_num > 16)
{
printf("please correct number 1~16\n");
}
pthread_t thr[thread_num];
srand(time(NULL));
for(i = 0; i < MAX_NUM ; i++)
data[i] = rand() % RANGE;
pthread_barrier_t barrier;
pthread_barrier_init(&barrier, NULL, thread_num);
for(i = 0; i < MAX_NUM ; i++)
{
buckets[i] = malloc(sizeof(int) * RANGE);
memset(buckets[i], 0, sizeof(int) * RANGE);
}
for(i = 0; i < thread_num ; i++)
{
arg[i].tid = i;
arg[i].thread_num = thread_num;
arg[i].data = data;
arg[i].buckets = buckets;
arg[i].barrier = &barrier;
}
timer_start(1);
for(i = 0; i < thread_num ; i++)
{
pthread_create(&thr[i], NULL, worker, &arg[i]);
}
for(i = 0 ; i < thread_num ; i++)
{
pthread_join(thr[i], NULL);
}
timer_stop(1);
for(i = 0 ; i < MAX_NUM ; i++)
for(j = 0; j < buckets[0][i] ; j++)
printf("%d\n",i);
printf("time elapsed : %lf sec\n",timer_read(1));
return 0;
}
void *worker(void *arg)
{
thread_args *args = (thread_args*) arg;
pthread_barrier_t * barrier = args->barrier;
int i, j;
int tid = args->tid;
int thread_num = args->thread_num;
int **buckets = args->buckets;
int *my_bucket = buckets[tid];
int *data = args->data;
int datafrom = (MAX_NUM * tid) / (thread_num);
int datato = (MAX_NUM * tid+1) / (thread_num);
for(i = datafrom ; i < datato ; i++)
my_bucket[data[i]]++;
pthread_barrier_wait(barrier);
int rangefrom = (RANGE * tid) / (thread_num);
int rangeto = (RANGE * (tid+1)) / (thread_num);
for(i = rangefrom ; i < rangeto ; i++)
for(j =1; j < thread_num ; j++)
buckets[0][i] += buckets[j][i];
return NULL;
}
' la fermata, 개발 > Pthread' 카테고리의 다른 글
False sharing 예제 (0) | 2019.02.19 |
---|---|
Thread Affinity 사용해보기 (0) | 2019.02.19 |
타일링을 이용한 행렬 곱셈 (0) | 2019.02.19 |
큐를 이용한 주사위 확률 구하기 (0) | 2019.02.19 |
fetch and add, test and set(TAS) 사용해보기 (0) | 2019.02.19 |