-
Notifications
You must be signed in to change notification settings - Fork 0
/
semaphore.c
53 lines (43 loc) · 1012 Bytes
/
semaphore.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
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
int semaphore = 1;
int state = 1;
pthread_mutex_t lock;
void wait(int *semaphore) {
while(*semaphore <= 0);
(*semaphore)--;
}
void signal(int *semaphore) {
(*semaphore)++;
}
void *thread_f(void *arg) {
int no = *((int *)arg);
int st = no;
while(1) {
pthread_mutex_lock(&lock);
wait(&semaphore);
if(state == st) {
printf("Thread [%d]-> %d\n", st, no);
no = no + 2;
state = 3 - st;
}
signal(&semaphore);
pthread_mutex_unlock(&lock);
usleep(100000);
}
pthread_exit(NULL);
}
int main() {
pthread_t id1, id2;
int odd = 1;
int even = 2;
pthread_mutex_init(&lock, NULL);
pthread_create(&id1, NULL, thread_f, (void *)&odd);
pthread_create(&id2, NULL, thread_f, (void *)&even);
pthread_join(id1, NULL);
pthread_join(id2, NULL);
pthread_mutex_destroy(&lock);
return 0;
}