[cs33211] OS Student question

Mikhail Nesterenko mikhail at cs.kent.edu
Tue Oct 30 18:50:24 EDT 2012


> 
> I was looking at your solution for Problem 4 from Homework #2 (implementing
> producer/consumer solution with locks and CVs). I believe there might be a
> problem: the actual operations of "producing to the queue" and "consuming
> from the queue" do not occur in a mutually exclusive area (i.e.
> producing/consuming from the queue happens when a thread does not own lock *
> b*.). Couldn't this cause problems?
> 
> For example: Thread 1 begins executing the producer() method and acquires
> lock *b*. Thread 2 begins executing the producer() method and is suspended
> when trying to acquire lock *b*. Thread 1 continues executing: check if
> queue is full, and unlocks *b*. Then, thread 2 acquires lock *b*, checks
> for a full queue, and unlocks *b*. Then, thread 1 writes to buff[rear], and
> then thread 2 writes to buff[rear], overwriting thread 1's value. This is
> possible because "producing to queue" does not exist in a mutually
> exclusive area. And so, this is a problem.

Well, making access to the shared buffer mutually exclusive solves the
producer/consumer problem the same way as the general mutual exclusion
problem. The idea is to make the solution as concurrent as
possible. For producer/consumer, it means allowing producer thread and
consumer thread concurrent access to the buffer as long as they are
not accessing the same item.

This is how the semaphore-based solution to the producer/consumer
problem (that we studied in class) works.

I might be missing something, but I believe the solution in the
homework operates the same way.  There is a single producer thread
running producer() function and a single consumer thread running
consumer() function. The producer thread is blocked (on "prod"
condition variable) if the buffer is full. The consumer thread is
blocked (on "cons" condition variable) if the buffer is
empty. Otherwise the threads are allowed to access the buffer
concurrently.

thanks,
--
Mikhail


More information about the cs33211 mailing list