Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <sys/eventfd.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <time.h>
- #include <errno.h>
- #define MAX_THREADS 2
- int val ;
- int ok2consume, ok2produce ;
- void *bufr ;
- int bufw = 1 ;
- void *producer(void *arg){
- while(1){
- int wtime = (random() % 10) + 1;
- read(ok2produce,bufr,sizeof(uint64_t));
- val = (random() % 255) + 1 ;
- printf("%d\n",val);
- write(ok2consume,&bufw,sizeof(uint64_t));
- sleep(wtime);
- }
- }
- void *consumer(void *arg){
- while(1){
- int wtime = (random() % 10) + 1 ;
- read(ok2consume,bufr,sizeof(uint64_t));
- printf("%d\n",val);
- write(ok2produce,&bufw,sizeof(uint64_t));
- sleep(wtime);
- }
- }
- int main(void){
- pthread_t TID[MAX_THREADS] ;
- int retval[MAX_THREADS];
- ok2produce = eventfd(1,EFD_SEMAPHORE);
- ok2consume = eventfd(0,EFD_SEMAPHORE);
- pthread_create(&TID[1], NULL, consumer,&val);
- pthread_create(&TID[0], NULL, producer,&val);
- printf("Producer ID = %ld created!\n",TID[0] ) ;
- printf("Consumer ID = %ld created!\n",TID[1] ) ;
- pthread_join(TID[0],(void*)&retval[0]);
- printf("Thread %ld terminated\n",TID[0]);
- pthread_join(TID[1],(void*)&retval[1]);
- printf("Thread %ld terminated\n",TID[1]);
- close(ok2consume);
- close(ok2produce);
- return 0 ;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement