2021年4月30日星期五

How would the producer consumer problem be solve if there was 1 producer and many consumers Buffer size of 1

How would the producer consumer problem be solved if there was 1 producer which provides a filename and two consumers which consume the filename.

The twist is that the buffer where the filename is added to is of size 1 meaning we can't have 2 copies one for each consumer to consume.

Both consumers have different logic to run for the same file.

I haven't included the exit condition logic but it will terminate threads when the filename equals EXIT.

Data is shared between producer/consumers with a pointer.

Shared Data:

    char* filenameBuffer;      pthread_mutex_t filenameMutex;      pthread_cond_t canProduceFilename;      pthread_cond_t canConsumeFilename;  

Currently I had the producer doing something like this.

Parent/Producer thread - Will loop till I want to exit.

while(!exit)  {      pthread_mutex_lock(filenameMutex);        //Check if the string is empty.      if(filenameBuffer != '\0')      {          p_thread_cond_wait(canProduceFilename, filenameMutex);      }        scanf("%s", filenameBuffer);        pthread_cond_signal(canConsumeFilename);      pthread_mutex_unlock(filenameMutex);  }    

Children/Consumer threads - Which we have 2 of.

while (!exit)  {      pthread_mutex_lock(filenameMutex);        //Loop until a string is produced.      while (filenameBuffer == '\0')      {         p_thread_cond_wait(canConsumeFilename, filenameMutex);      }        //Do something with filename, not relevant for solution.        pthread_mutex_unlock(filenameMutex);  }    

So how would I be able to consume the filename inside the consumers without controlling the order each consumer thread. I don't want to force the order of which consumer can run first as that ruins the point of multithreading.

I'll stick around if there is any clarification or more information required.

Any discussion or guidance would be greatly appreciated.

Kind regards.

https://stackoverflow.com/questions/67320037/how-would-the-producer-consumer-problem-be-solve-if-there-was-1-producer-and-man April 29, 2021 at 11:06PM

没有评论:

发表评论