In this project, we will study to apply multithreaded programming to implement a
ID: 3596969 • Letter: I
Question
In this project, we will study to apply multithreaded programming to implement a producer-consumer solution that prints a sequence of consecutive integers starting from 0, using a fixed size buffer (i.e, bounded buffer). As we mentioned in the class, multithreaded programming can be supported in the user level, more specifically, libraries in the user level. The library we will use for this project is called pthread. In this project, a producer repeatedly generates the next consecutive integer and insert it into the slot indicated by the flag in; a consumer repeatedly pick up an item from the slot indicated by the flag out. More precisely, your code should achieve the following: • Integers should be printed consecutively, i.e, 0, 1, 2, ...up to a certain integer. • The buffer size can be larger than 1. • There can be multiple producer threads and multiple consumer threads.
Explanation / Answer
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include<pthread.h>
#include<errno.h>
#include <stdlib.h>
#include<time.h>
int flag = 0;
int item = 0;
int count = 0;
void *producer()
{
while(1){
while (flag == 1)
sleep(rand()%3);
count++;
if (flag == 0){
item++;
sleep(1);
if (item == 10)
flag = 1;
}
}
return NULL;
}
void *consumer()
{
while(1){
while (flag == 0)
sleep(rand()%3);
count++;
if (flag == 1){
item--;
sleep(1);
if (item == 0)
flag = 0;
}
}
return NULL;
}
int main()
{
pthread_t tid1,tid2;
srand(time(NULL));
pthread_create(&tid1, NULL, producer, NULL);
pthread_create(&tid2, NULL, consumer, NULL);
while(1){
sleep(1);
printf("%d ",item);
if (count == 50)
break;
}
exit(0);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.