What is the need of a while in a producer-consumer?

Asked

Viewed 83 times

4

I’m used to programming using this while in problems involving synchronization of threds because that’s how API’s usually ask you to do it, but I’ve never wondered why it is. I am taking a course of operating systems to review the concepts I learned at university and I came across this doubt.

exemplo de um cenário produtor-consumidor

This brief video (in English) talks about mutual exclusion and the classic consumer producer. In it, the teacher says that the consumer should wait in a loop while (condição) until he is notified by a producer. Why not use a simple if instead of a while?

The problem addressed in the video is the following: Producers (competing threads) add values to the list and when this list fills up, the consimidor is notified. The consimidor should then display the contents of the list and then clear it.

In the video, she also says that the implementation of wait must make a unlock in the mutex m and then make a lock again. I didn’t understand the need for this unlock/lock inside the Wait.

Can anyone clarify these two doubts? If possible, exemplify in C.

1 answer

1

I found the answer to the question. Basically it was answered in the course itself in this video.

The while is necessary because there may be more than one Consumer. When a thread consumer T1 which is locked in a wait is awakened, there is no guarantee that it will be this same thread T1 the next one that will be able to lock the mutex. In that time interval another thread consumer T2 could have acquired the lock and cleared the list. If it was a if instead of a while, case the thread T1 could acquire the lock right after T2 clear the list, T1 would remake an operation that had already been done by T2. In this particular example there would be no major problems, as the Consumer just prints and clears the list, no "crucial" operation is done.

In the video, she also says that the implementation of Wait should make a Unlock no mutex m and soon after make a lock again. I did not understand the need for that Unlock/lock within Wait.

The answer to this question is that if Wait didn’t do Unlock, all the other threads that tried to lock this mutex wouldn’t succeed, because Wait would be with the lock, that is, there would be a deadlock. That’s why Wait should do a Unlock on mutex. The Wait implementation should make sure to put in the waiting list the thread that requested the lock, release the mutex so that other threads can Locks, wait until the conditional variable list_full is flagged and then remove the thread from the list and reacquire the mutex lock so that the critical section print_and_remove_all() can be safely executed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.