15-440/15-640 Fall 2012. Microquiz Q2 Assigned Thursday: 09/13/2012 Due Monday 09/17/2012, 10:00pm Instructions: 1. Retrieve a copy of the file cvar.tar. This is available at: /afs/cs.cmu.edu/academic/class/15440-f12/Q2/cvar.tar It is also available via autolab. 2. Extract the files into a private directory 3. Modify the code in the file cvar-impl.go to implement the Mutex and Cond data types, as defined in the documentation below. The functions are defined by the API given in the file cvar-api.go, and are documented below. These functions closely match the definitions in the Go sync package. You must implement these functions using only standard Go data structures and constructs, such as channels, goroutines, select, etc. You should not import any other library. 4. Make sure your code passes the tests performed by running "go test" within this directory. 5. Hand in your file cvar-impl.go via Autolab. Directions for this will be provided later. ********************************************************************** API Definition ********************************************************************** type Mutex struct { // contains filtered or unexported fields } A Mutex is a mutual exclusion lock. Mutexes can be created as part of other structures; Mutexes should be created by calling NewMutex func NewMutex() *Mutex NewMutex creates a Mutex. It is initially unlocked. func (m *Mutex) Lock() Lock locks m. If the lock is already in use, the calling goroutine blocks until the mutex is available. func (m *Mutex) Unlock() Unlock unlocks m. It is a run-time error if m is not locked on entry to Unlock. A locked Mutex is not associated with a particular goroutine. It is allowed for one goroutine to lock a Mutex and then arrange for another goroutine to unlock it. type Cond struct { // contains filtered or unexported fields } Cond implements a condition variable, a rendezvous point for goroutines waiting for or announcing the occurrence of an event. Each Cond has an associated Mutex m, which must be held when changing the condition and when calling the Wait method. func NewCond(m *Mutex) *Cond NewCond returns a new Cond with Mutex m. func (c *Cond) Broadcast() Broadcast wakes all goroutines waiting on c. It is allowed but not required for the caller to hold c.m during the call. func (c *Cond) Signal() Signal wakes one goroutine waiting on c, if there is any. It is allowed but not required for the caller to hold c.m during the call. func (c *Cond) Wait() Wait atomically unlocks c.m and suspends execution of the calling goroutine. After later resuming execution, Wait locks c.m before returning. Unlike in other systems, Wait cannot return unless awoken by Broadcast or Signal. Because c.m is not locked when Wait first resumes, the caller typically cannot assume that the condition is true when Wait returns. Instead, the caller should Wait in a loop: c.m.Lock() for !condition() { c.Wait() } ... make use of condition ... c.m.Unlock()