#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int SIZE=50000;
int TAIL;
int HEAD;
pid_t MYARRAY[50000];
pthread_mutex_t mutex;
pthread_cond_t condInserted;
pthread_cond_t condRemoved;
int isFull(){
if((HEAD+1)%SIZE==TAIL){
return 1;
}
return 0;
}
int isEmpty(){
if(HEAD==TAIL){
return 1;
}
return 0;
}
void * thread1(){
while(1){
pthread_mutex_lock(&mutex);//mutex object referenced by mutex shall be locked
if(isFull()){
printf("Full queue");
pthread_cond_wait(&condRemoved,&mutex);
}
pid_t tid = gettid();
HEAD = (HEAD+1)%SIZE;
MYARRAY[HEAD] = tid;
printf("\nWriter:%d\n",tid);
pthread_mutex_unlock(&mutex);//mutex object referenced by mutex be unlocked
pthread_cond_signal(&condInserted);//call unblocks at least one of the threads that are blocked on the specified condition variable cond
usleep(300000);
}
}
void* thread2(){
while(1){
pthread_mutex_lock(&mutex);
pid_t a = -1;
pid_t tid = gettid();//returns the caller's thread ID
if(isEmpty()){
printf("Empty queue");
pthread_cond_wait(&condInserted,&mutex);//used to block on a condition variable
}
TAIL = (TAIL+1)%SIZE;
a = MYARRAY[TAIL];
MYARRAY[TAIL] = -1;
printf("\n\t\t\t\t\t\t\t\tReader : %d,READ:%d\n",tid,a);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&condRemoved);
usleep(200000);//suspends execution of the calling thread
//for (at least) usec microseconds
}
}
int main() {
SIZE = 50000;
TAIL=HEAD=0;
pthread_mutex_init(&mutex,NULL);// initialises the mutex
pthread_cond_init(&condInserted,NULL);//initialises the condition variable
pthread_cond_init(&condRemoved,NULL);//initialises the condition variable
pthread_t writer_threads[20];
pthread_t reader_threads[2];
for(int i=0;i<20;i++){
pthread_create(&writer_threads[i],NULL,&thread1,NULL);
}
for (int i = 0; i < 2; i++) {
pthread_create(&reader_threads[i], NULL, &thread2, NULL);
}
for (int i = 0; i < 20; i++) {
pthread_join(writer_threads[i], NULL);
}
for (int i = 0; i < 2; i++) {
pthread_join(reader_threads[i], NULL);
}
pthread_mutex_destroy(&mutex);//shall destroy the mutex object referenced by mutex
pthread_cond_destroy(&condInserted);//destroy the given condition variable specified by cond
pthread_cond_destroy(&condRemoved);
return 0;
}
Comments
Post a Comment