The document describes an unbounded buffer solution using producer-consumer pattern with locks. It includes code for the producer, consumer, and main functions. The producer acquires a lock, creates an item, increments the shared counter, and releases the lock. The consumer acquires the lock, checks if an item is available, destroys the item if so, decrements the counter, and releases the lock.
It also summarizes how to implement locks in NachOS using semaphores. The semaphore lock class maintains a lock holder thread and wait queue. Acquire checks for the lock and adds the thread to the queue if held. Release checks the queue and resumes a waiting thread.
Finally, it provides an
2. Unbounded buffer Producer-Consumer with locks In this solution the producer is free to create items at any time, the consumer doesn't care. But if the consumer want to take an item, it needs to check the amount of items in stock, if the amount is zero, it will do nothing.
3. Unbounded buffer Producer-Consumer with locks function: producer start repeat on true l->Acquire(); createItem(); in_stock++; l->Release(); end function: consumer start repeat on true if in_stock == 0 Do nothing else in_stock > 0 l->Acquire(); destroyItem(); in_stock--; l->Release(); end Lock: l integer: in_stock function: main start in_stock = 0 call producer(); call consumer(); end
4. Implementing locks in NachOS using Semaphores class SemaphoreLock KernelThread: LockHolder = null; ThreadQueue: waitQueue; function: SemaphoreAcquire start bool: status = Interrupt nachos machine. check if the current thread have this lock. thread = current thread if lockHolder != null waitQueue = waitfor(thread); then sleep the thread. else waitQueue.acquire(thread); lockHolder = current thread; restore the nachos machine with the new status; end function: SemaphoreRelease start bool: status = Interrupt nachos machine if waitQueue is not empty lockHolder(current thread) is ready to run now end end
5. Implement a condition variable in NachOS using semaphores. Lock cl; SemaphoreLinkedList waitQueue; function: Constructor(Lock *cl) start conditionLock = cl; waitQueue = getSemaphoreLinkedList(); end function: sleep start check if the current thread has the lock sleeper = new Semaphore(); add sleeper to the WaitQueue cl->release(); sleeper.P() cl-> acquire(); end function: wake start check if the current thread has the lock if waitQueue is not empty Remove the first thread && use V(); end function: wakeall start check if the current thread has the lock repeat until the WaitQueue are empty call wake(); end