Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rdemeter
GitHub Repository: rdemeter/so
Path: blob/master/lab9/prodcons2.c
221 views
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <unistd.h>
4
#include <time.h>
5
#include <pthread.h>
6
#include <semaphore.h>
7
8
#define NUM_TOTAL_BUFFERS 5
9
#define DATA_LENGTH 20
10
11
char buffers[NUM_TOTAL_BUFFERS];
12
sem_t empty, full;
13
pthread_mutex_t mutex;
14
15
void *producer()
16
{
17
int i, writePt = 0;
18
char data;
19
20
for(i=0; i < DATA_LENGTH; i++)
21
{
22
sem_wait(&empty);
23
pthread_mutex_lock(&mutex);
24
data = 'A' + rand() % 25;
25
buffers[writePt] = data;
26
printf("producer: buffer[%d]=%c\n", writePt, data);
27
writePt = (writePt + 1) % NUM_TOTAL_BUFFERS;
28
pthread_mutex_unlock(&mutex);
29
sem_post(&full);
30
}
31
}
32
33
void* consumer()
34
{
35
int i, readPt = 0;
36
char data;
37
38
for(i=0; i < DATA_LENGTH; i++)
39
{
40
sem_wait(&full);
41
pthread_mutex_lock(&mutex);
42
data = buffers[readPt];
43
printf("\t\tconsumer: buffer[%d]=%c\n", readPt, data);
44
readPt = (readPt + 1) % NUM_TOTAL_BUFFERS;
45
pthread_mutex_unlock(&mutex);
46
sem_post(&empty);
47
}
48
}
49
50
int main(void)
51
{
52
sem_init(&full, 0, 0);
53
sem_init(&empty, 0, NUM_TOTAL_BUFFERS);
54
55
pthread_t prod, cons;
56
pthread_create(&prod, NULL, producer, NULL);
57
pthread_create(&cons, NULL, consumer, NULL);
58
59
pthread_join(prod, NULL);
60
pthread_join(cons, NULL);
61
62
sem_destroy(&full);
63
sem_destroy(&empty);
64
65
printf("done!\n");
66
return 0;
67
}
68
69