-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultiThreading.c
80 lines (71 loc) · 1.79 KB
/
multiThreading.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
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <semaphore.h>
/*gcc -o multithread multiThreading.c -lpthread*/
#define THREAD_NUM 8
sem_t semEmpty;
sem_t semFull;
pthread_mutex_t mutexBuffer;
int buffer[10];
int count = 0;
void* producer(void* args) {
while (1) {
// Produce
int x = rand() % 100;
sleep(1);
// Add to the buffer
sem_wait(&semEmpty);
pthread_mutex_lock(&mutexBuffer);
buffer[count] = x;
count++;
pthread_mutex_unlock(&mutexBuffer);
sem_post(&semFull);
}
}
void* consumer(void* args) {
while (1) {
int y;
// Remove from the buffer
sem_wait(&semFull);
pthread_mutex_lock(&mutexBuffer);
y = buffer[count - 1];
count--;
pthread_mutex_unlock(&mutexBuffer);
sem_post(&semEmpty);
// Consume
printf("Got %d\n", y);
sleep(1);
}
}
int main(int argc, char* argv[]) {
srand(time(NULL));
pthread_t th[THREAD_NUM];
pthread_mutex_init(&mutexBuffer, NULL);
sem_init(&semEmpty, 0, 10);
sem_init(&semFull, 0, 0);
int i;
for (i = 0; i < THREAD_NUM; i++) {
if (i > 0) {
if (pthread_create(&th[i], NULL, &producer, NULL) != 0) {
perror("Failed to create thread");
}
} else {
if (pthread_create(&th[i], NULL, &consumer, NULL) != 0) {
perror("Failed to create thread");
}
}
}
for (i = 0; i < THREAD_NUM; i++) {
if (pthread_join(th[i], NULL) != 0) {
perror("Failed to join thread");
}
}
sem_destroy(&semEmpty);
sem_destroy(&semFull);
pthread_mutex_destroy(&mutexBuffer);
return 0;
}