0% found this document useful (0 votes)
13 views7 pages

Homework Week 8 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views7 pages

Homework Week 8 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Homework Week-9

Solve the following problem using POSIX pthread







Code:
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#de ne BUFFER_SIZE 5

typedef int bu er_item;

bu er_item bu er[BUFFER_SIZE];
int in = 0, out = 0;

pthread_mutex_t mutex;
sem_t empty, full;

int insert_item(bu er_item item) {


sem_wait(&empty);
pthread_mutex_lock(&mutex);

ff
fi
ff
ff
ff
bu er[in] = item;
in = (in + 1) % BUFFER_SIZE;

pthread_mutex_unlock(&mutex);
sem_post(&full);
return 0;
}

int remove_item(bu er_item *item) {


sem_wait(&full);
pthread_mutex_lock(&mutex);

*item = bu er[out];
out = (out + 1) % BUFFER_SIZE;

pthread_mutex_unlock(&mutex);
sem_post(&empty);
return 0;
}

void *producer(void *param) {


bu er_item item;
while (true) {
sleep(rand() % 3);
item = rand();

if (insert_item(item) == 0) {
prin ("produced %d\n", item);
}
ff
ff
tf
ff
ff
}
}

void *consumer(void *param) {


bu er_item item;
while (true) {
sleep(rand() % 3);

if (remove_item(&item) == 0) {
prin ("consumed %d\n", item);
}
}
}

int main(int argc, char *argv[]) {


int sleep_ me, num_producers, num_consumers;

if (argc != 4) {
return -1;
}

sleep_ me = atoi(argv[1]);
num_producers = atoi(argv[2]);
num_consumers = atoi(argv[3]);

pthread_mutex_init(&mutex, NULL);

sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
ff
ti
tf
ti
pthread_t producers[num_producers], consumers[num_consumers];
for (int i = 0; i < num_producers; i++) {
pthread_create(&producers[i], NULL, producer, NULL);
}
for (int i = 0; i < num_consumers; i++) {
pthread_create(&consumers[i], NULL, consumer, NULL);
}

sleep(sleep_ me);

prin ("done");
return 0;
}

Screenshot of Result:
tf
ti

You might also like