I have a question about the ordering of semaphores(muxtex, empty) in the bounded buffer problem shown in the book "Operating Systems Concepts" by gagne. The below are the two images of the code i'm referring to.

First) Bounded buffer.

Second) Insert Method.

My question is: what is the reason to have empty.acquire() before mutex.acquire() in the insert method? isn't it more clear if mutex.acquire() comes before empty.acquire? I know in terms of functionality, the order does not matter. But is there a reason why the author calls the empty.acquire before mutex.acquire?

enter image description here

enter image description here

有帮助吗?

解决方案

The order is important for the case when the buffer is full. empty.acquire() has the effect of blocking the thread until there is at least one free slot in the buffer before attempting to add an item to the buffer.

If reversed, the function would look like:

public void insert(Object item) {
    mutex.acquire();
    empty.acquire();
    ...

If this method is called when the buffer is full, mutex will be acquired while the thread is blocked on empty.acquire(). Then, if another thread calls remove() to free up a buffer slot, it will block on mutex.acquire(). Now, no new element can be added, because the buffer is full and all attempts to remove an object will block.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top