Right way to wait for condition from another goroutine?

Hi,
I’m very new to Go and currently learning concurrency. I need a way to concurrently execute a maximum of two tasks at a time. Here is what I’ve coded:

func ExecuteTask(wg *sync.WorkGroup) {
    var wg2 sync.WorkGroup
    wg2.Add(1)
    go CheckTotal(&wg2)
    wg2.Wait()
    //Rest of the code with total--, then wg.Done()
}

var total int = 0
var mut sync.Mutex

func CheckTotal(wg *sync.WorkGroup) {
    for {
        if total < 2 {
           mut.Lock()
           total++
           mut.Unlock()
           wg.Done()
       }
    }
}

func main() {
    var wg sync.WorkGroup
    wg.Add(10)
    for i:=0; i<10; i++ {
        ExecuteTask(&wg)
    }
    wg.Wait()
}

This works but using the for loop inside the CheckTotal feels hacky. What would be the correct way to accomplish this?
Thank you

The usual way of doing this is with channels, eg

http://jmoiron.net/blog/limiting-concurrency-in-go/

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.