How to correctly use sync.Cond?

前端 未结 8 810
忘了有多久
忘了有多久 2021-02-01 16:11

I\'m having trouble figuring out how to correctly use sync.Cond. From what I can tell, a race condition exists between locking the Locker and invoking the condition\'s Wait meth

8条回答
  •  温柔的废话
    2021-02-01 16:58

    I finally discovered a way to do this and it doesn't involve sync.Cond at all - just the mutex.

    type Task struct {
        m       sync.Mutex
        headers http.Header
    }
    
    func NewTask() *Task {
        t := &Task{}
        t.m.Lock()
        go func() {
            defer t.m.Unlock()
            // ...do stuff...
        }()
        return t
    }
    
    func (t *Task) WaitFor() http.Header {
        t.m.Lock()
        defer t.m.Unlock()
        return t.headers
    }
    

    How does this work?

    The mutex is locked at the beginning of the task, ensuring that anything calling WaitFor() will block. Once the headers are available and the mutex unlocked by the goroutine, each call to WaitFor() will execute one at a time. All future calls (even after the goroutine ends) will have no problem locking the mutex, since it will always be left unlocked.

提交回复
热议问题