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