forked from remzi-arpacidusseau/ostep-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
throttle.c
48 lines (37 loc) · 908 Bytes
/
throttle.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
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include "common.h"
#include "common_threads.h"
#ifdef linux
#include <semaphore.h>
#elif __APPLE__
#include "zemaphore.h"
#endif
sem_t s;
void *child(void *arg) {
Sem_wait(&s);
printf("child %lld\n", (long long int) arg);
sleep(1);
Sem_post(&s);
return NULL;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "usage: throttle <num_threads> <sem_value>\n");
exit(1);
}
int num_threads = atoi(argv[1]);
int sem_value = atoi(argv[2]);
Sem_init(&s, sem_value);
printf("parent: begin\n");
pthread_t c[num_threads];
int i;
for (i = 0; i < num_threads; i++)
Pthread_create(&c[i], NULL, child, (void *) (long long int)i);
for (i = 0; i < num_threads; i++)
Pthread_join(c[i], NULL);
printf("parent: end\n");
return 0;
}