if there is 1 producer, 1 consumer and a buffer of >1 size is insert mutex required? is remove mutex required?
if there is 1 producer, 1 consumer and a buffer of 1 size is insert mutex required? is remove mutex required?
if there is >1 producer, >1 consumer and a buffer of 1 size is insert mutex required? is remove mutex required?
Can someone explain how you get to answer these questions. I know that two threads should never read from a the buffer while its being written into, but doesn't that mean that all of the scenarios require both mutexs?
Answers from professor: first case is yes, second two are no because when buffer is nonempty that is equivalent to a full buffer. When the buffer is empty the consumer is blocked. When the buffer contains an item the producer is blocked. So mutual exclusion is guaranteed with out using mutex. Which didn't help with understanding why that's the case. Good thing more experience has been had since this post was made.
Consider the following linked list queue pop method:
Object pop() {
if(this.head != null) {
Node n = this.head;
this.head = n.next;
return n.data;
}
return null;
}
This method is not thread safe. Consider what would happen if the thread paused after executing line 3, and another thread calls pop; both threads would get the same object.
Mutexes ensure that two threads cannot access the same resource at the same time, protecting against this 'race condition'. By ensuring that only one thread can pop an element at a time, the consistency of the queue is maintained.
It is possible to implement a queue without using mutexes (ex. Java's ConcurrentLinkedList), but it is much more difficult.