开发者

ProducerConsumer problem

I am trying to translate the scenario below using threads.

procA {
     while (TRUE) {
     
      update(x);
      
     retrieve(y);
      }
     }
     procB {
     while (TRUE) {
     retrieve(x);
     
     update(y);
     
      }
     }

Have written the code for this which I have provided below:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

#define WORK_SIZE 10
pthread_mutex_t work_mutex;
int wa1[WORK_SIZE];
int wa2[WORK_SIZE];
void *funA(void *);
void *funB(void *);
int main(){

 pthread_t tid1,tid2;

 if(pthread_create(&tid1,NULL,funA,(void *)wa1))
    perror("pthread_create");
 if(pthread_create(&tid2,NULL,funB,(void *)wa2))
   perror("pthread_create");

 pthread_join(tid1,NULL);
  pthread_join(tid2,NULL);

  return 0;
 }


  void *funA(void *ptr){
  int *x=ptr;
   int i=0,j,num;
   //sleep(1);
  while(i<=10){
    num=rand();
   *x=num;
    x+1;
    j=*wa2;
  printf("A: %d\n",j);
    wa2+1;
     i++;
      }
   return NULL;
    }

 void * funB(void *ptr){
   int *y=ptr;
   int a=0,b,num;
    while(a<=10){
     num=rand();
     b=*wa1;
    printf("B: %d\n",b);
     wa1+1;
    *y=num;
    y+1;
    a++;
   }
    return NULL;
   }

I am required to implement MUTEX but that will come later into the picture. For now as my per my understanding, both the threads should in progress simultaneously and hence the address pointed by *wa1 and *wa2 should be getting updated simultaneously. It seems I am missing something because of which the output getting generated is : Included infinite loop. Updated o/p depicted below(only a part of the output)

A: 1258442020
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
B: 1317969989
A: 803738656
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
B: 1851766329
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464

Seems like after the infinite loop, a context switch happens but I am still not clear on the output. The random function should generate a new number but rather the same number is getting repeated. Any suggestions please and how can this be termed as a producer -consumer problem How can I impleme开发者_如何转开发nt this problem is a better manner than the one I have implemented

thanks.


The ten iteration are just so few that they are handled before a context switch can happen, so you wouldn't see any concurrency. I'm sorry that I can't really tell anything from your code because it lacks indentation, comments and good variable names.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜