You are on page 1of 4

Aim-Producer-Consumer Problem Using Threading Concept

Roll No.s104179

Code-
#include<stdio.h>

#include<time.h>

#include<pthread.h>

void *producer();

void *consumer();

int buf[50];

int count,cnt;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
int main()

pthread_t prod,cons;

pthread_create(&prod,NULL,producer,NULL);

pthread_create(&cons,NULL,consumer,NULL);

pthread_join(prod,NULL);

pthread_join(cons,NULL);

return(0);

void *producer()

int i;

for(i=1;i<10;i++)

{
pthread_mutex_lock(&mutex);buf[count]=i;

count++;

printf("\n The Item %d is produced",i);

pthread_mutex_unlock(&mutex);

sleep(1);

///////dgggdg

void *consumer()

int j;

for(j=1;j<10;j++)

pthread_mutex_lock(&mutex);

if(count!=0)

buf[cnt]=j;

printf("\n The Item %d is consumed",j);

pthread_mutex_unlock(&mutex);

sleep(2);

}
Output:-
sanket@linuxmint ~ $ cc ptoc.c

/tmp/ccILRp8G.o: In function `main':

ptoc.c:(.text+0x2a): undefined reference to `pthread_create'

ptoc.c:(.text+0x4f): undefined reference to `pthread_create'

ptoc.c:(.text+0x63): undefined reference to `pthread_join'

ptoc.c:(.text+0x77): undefined reference to `pthread_join'

collect2: ld returned 1 exit status

sanket@linuxmint ~ $ cc ptoc.c -lpthread

sanket@linuxmint ~ $ ./a.out

The Item 1 is produced

The Item 1 is consumed

The Item 2 is produced

The Item 2 is consumed

The Item 3 is produced

The Item 4 is produced

The Item 3 is consumed

The Item 5 is produced

The Item 6 is produced

The Item 4 is consumed

The Item 7 is produced

The Item 8 is produced

The Item 5 is consumed

The Item 9 is produced


The Item 6 is consumed

The Item 7 is consumed

The Item 8 is consumed

The Item 9 is consumedsanket@linuxmint ~ $

You might also like