-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_barrier_2.c
More file actions
55 lines (42 loc) · 1.14 KB
/
Copy pathtest_barrier_2.c
File metadata and controls
55 lines (42 loc) · 1.14 KB
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
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#define NUM_THREADS 10
pthread_barrier_t barrier;
void *thread_func(void *arg) {
long thread_id = (long)arg;
printf("Thread %ld: Before barrier\n", thread_id);
// Wait for all threads to reach the barrier
pthread_barrier_wait(&barrier);
printf("Thread %ld: After barrier\n", thread_id);
pthread_exit(NULL);
}
void *print_hello(void *arg) {
for (int ii = 0; ii < 4; ++ii) {
printf("hello!\n");
for (int i = 0; i < 1e9; ++i) {
// Simulate some work
}
}
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
pthread_t hellothread;
void *pret;
// Initialize the barrier
pthread_barrier_init(&barrier, NULL, NUM_THREADS);
// Create threads
pthread_create(&hellothread, NULL, print_hello, NULL);
for (int i = 0; i < NUM_THREADS; i++) {
pthread_create(&threads[i], NULL, thread_func, (void*)(long)i);
}
// Wait for all threads to finish
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], &pret);
}
pthread_join(hellothread, &pret);
// Destroy the barrier
pthread_barrier_destroy(&barrier);
return 0;
}