/
pth_busy_bar1.c
96 lines (79 loc) · 2.43 KB
/
pth_busy_bar1.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/* File:
* pth_busy_bar1.c
*
* Purpose:
* Use busy wait barriers to synchronize threads.
*
* Compile: gcc -g -Wall -O0 -o pth_busy_bar1 pth_busy_bar1.c -lpthread
* Run: ./pth_busy_bar1 <thread count>
*
* Input:
* none
* Output:
* Time for BARRIER_COUNT barriers
*
* Note: Use -O0 to turn off compiler optimization
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "timer.h"
#define BARRIER_COUNT 1000
int thread_count;
int barrier_thread_counts[BARRIER_COUNT];
pthread_mutex_t barrier_mutex;
void Usage(char* prog_name);
void *Thread_work(void* rank);
/*--------------------------------------------------------------------*/
int main(int argc, char* argv[]) {
long thread, i;
pthread_t* thread_handles;
double start, finish;
if (argc != 2) Usage(argv[0]);
thread_count = strtol(argv[1], NULL, 10);
thread_handles = malloc (thread_count*sizeof(pthread_t));
for (i = 0; i < BARRIER_COUNT; i++)
barrier_thread_counts[i] = 0;
pthread_mutex_init(&barrier_mutex, NULL);
GET_TIME(start);
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], (pthread_attr_t*) NULL,
Thread_work, (void*) thread);
for (thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], NULL);
}
GET_TIME(finish);
printf("Elapsed time = %e seconds\n", finish - start);
pthread_mutex_destroy(&barrier_mutex);
free(thread_handles);
return 0;
} /* main */
/*--------------------------------------------------------------------
* Function: Usage
* Purpose: Print command line for function and terminate
* In arg: prog_name
*/
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <number of threads>\n", prog_name);
exit(0);
} /* Usage */
/*-------------------------------------------------------------------
* Function: Thread_work
* Purpose: Run BARRIER_COUNT barriers
* In arg: rank
* Global var: thread_count, barrier_thread_counts, barrier_mutex
* Return val: Ignored
*/
void *Thread_work(void* rank) {
// long my_rank = (long) rank;
int i;
for (i = 0; i < BARRIER_COUNT; i++) {
/* Start Barrier */
pthread_mutex_lock(&barrier_mutex);
barrier_thread_counts[i]++;
pthread_mutex_unlock(&barrier_mutex);
while (barrier_thread_counts[i] < thread_count);
/* End Barrier */
}
return NULL;
} /* Thread_work */