-
Notifications
You must be signed in to change notification settings - Fork 1k
/
barrier.c
72 lines (54 loc) · 1.55 KB
/
barrier.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
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "common_threads.h"
// If done correctly, each child should print their "before" message
// before either prints their "after" message. Test by adding sleep(1)
// calls in various locations.
// You likely need two semaphores to do this correctly, and some
// other integers to track things.
typedef struct __barrier_t {
// add semaphores and other information here
} barrier_t;
// the single barrier we are using for this program
barrier_t b;
void barrier_init(barrier_t *b, int num_threads) {
// initialization code goes here
}
void barrier(barrier_t *b) {
// barrier code goes here
}
//
// XXX: don't change below here (just run it!)
//
typedef struct __tinfo_t {
int thread_id;
} tinfo_t;
void *child(void *arg) {
tinfo_t *t = (tinfo_t *) arg;
printf("child %d: before\n", t->thread_id);
barrier(&b);
printf("child %d: after\n", t->thread_id);
return NULL;
}
// run with a single argument indicating the number of
// threads you wish to create (1 or more)
int main(int argc, char *argv[]) {
assert(argc == 2);
int num_threads = atoi(argv[1]);
assert(num_threads > 0);
pthread_t p[num_threads];
tinfo_t t[num_threads];
printf("parent: begin\n");
barrier_init(&b, num_threads);
int i;
for (i = 0; i < num_threads; i++) {
t[i].thread_id = i;
Pthread_create(&p[i], NULL, child, &t[i]);
}
for (i = 0; i < num_threads; i++)
Pthread_join(p[i], NULL);
printf("parent: end\n");
return 0;
}