0%

How to write semaphore on MAC

No shit, just following the code. OSX based on POSIX that it can’t use sem_init to initial the semaphore and it can’t use sem_destroy to destroy the semaphore, too.

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
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
static sem_t *s;
int a, b, c;
void getA() {
sleep(10);
a = 3;
printf("a: %d\r\n", a);
sem_post(s);
pthread_exit("Thread is done");
}
void getB() {
sleep(5);
b = 10;
printf("b: %d\r\n", b);
sem_post(s);
pthread_exit("Thread is done");
}
void getC() {
sem_wait(s);
sem_wait(s);
c = a+b;
printf("c: %d\r\n", c);
sleep(10);
pthread_exit("Thread is done");
}
int main(int argc, char *argv[]) {
pthread_t tid1, tid2, tid3;
sem_unlink("s");
s = sem_open("s", O_CREAT, S_IRUSR | S_IWUSR, 0);
if(pthread_create(&tid1, NULL, (void*)getA, NULL)) {
}
if(pthread_create(&tid2, NULL, (void*)getB, NULL)) {
}
if(pthread_create(&tid3, NULL, (void*)getC, NULL)) {
}
pthread_join(tid3, NULL);
sem_close(s);
sem_unlink("s");
return 0;
}