Skip to content

Chatper 6 - Excersie 2 - Doubt #7

Description

@nivekithan

In previous chapters, we saw the TryLock() operation on mutexes. This is a nonblocking call that returns immediately without waiting. If the lock is not available, the function returns false; otherwise, it locks the mutex and returns true.
Can you write a similar non-blocking function called TryWait() on our implementation of a waitgroup from listing 6.8? This function will return immediately with false if the waitgroup is not done; otherwise, it returns true.

From my understanding is that TryWait should not block if the waitgroup is not done but the solution for it is

func (wg *WaitGrp) TryWait() bool {
	wg.cond.L.Lock()
	result := wg.groupSize == 0
	wg.cond.L.Unlock()
	return result
}
> wg.cond.L.Lock()

Doesn't this line block the current goroutine until it got exclusive access to cond.L mutex ?

Event though cond.L mutex is internal and get's blocked only for short time by these methods Add, Done, Wait. I was hoping we can implement a solution similar to Excerise 4.3 . Where we implement TryReadLock for our mutex.

Sharing solution for reference

func (rw *ReadWriteMutex) TryReadLock() bool {
    if rw.readersLock.TryLock() {
        globalSuccess := true
        if rw.readersCounter == 0 {
            globalSuccess = rw.globalLock.TryLock()
        }
        if globalSuccess {
            rw.readersCounter++
        }
        rw.readersLock.Unlock()
        return globalSuccess
    } else {
        return false
    }
}

Anyways my doubt is that is there any way to implement TryWait without waiting for cond.L.Lock too ?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions