Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<pthread.h>
- #include<sys/types.h>
- #include<unistd.h>
- #include<stdlib.h>
- #include<semaphore.h>
- #include<windows.h>
- #define sleep(n) Sleep(n*500)
- #define MAX 5
- sem_t empty,full,mutex;
- char buf[MAX];
- char character = 'A';
- void* thread_fun1(void* arg)
- {
- int i;
- printf("--------------------\n");
- printf("PRODUCER CONSUMER\nOleh : Mirra Ariesta\n");
- printf("--------------------\n");
- for(i=0; i<MAX; i++){
- sem_wait(&empty);
- sem_wait(&mutex);
- buf[i]=character++;
- printf("item produced is %c\n",buf[i]);
- sem_post(&mutex);
- sem_post(&full);
- sleep(1);
- }
- char* name = "producer\n";
- pthread_exit(name);
- }
- void * thread_fun2(void* arg){
- int j;
- for(j=0; j<MAX; j++){
- sem_wait(&full);
- sem_wait(&mutex);
- sleep(1);
- printf("consumed item is:%c\n",buf[j]);
- sem_post(&mutex);
- sem_post(&empty);
- sleep(5);
- }
- char* name = "consumer\n";
- pthread_exit(name);
- }
- int main(){
- pthread_t pid1,pid2;
- sem_init(&empty,0,MAX);
- sem_init(&full,0,0);
- sem_init(&mutex,1,1);
- void *status;
- pthread_create(&pid1,NULL,thread_fun1,NULL);
- pthread_create(&pid2,NULL,thread_fun2,NULL);
- pthread_join(pid1,&status);
- printf("the exited status of 1st is %s\n",(char*)status);
- pthread_join(pid2,&status);
- printf("the exited status %s\n",(char*)status);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment