思路:将协程编号为[0,n-1]。创建n个锁,分别对应[0,n-1],初始化时将所有锁上锁,之后启动n个协程,对于每个协程,需要先获取自身对应的锁,获取到执行完后解放下一个协程的锁。最后别忘记启动完n个协程后将第0个锁解锁,否则这n个协程就死锁了。
package main
import (
"fmt"
"sync"
"time"
)
func main() {
nbGoroutine := 10
locks := make([]sync.Mutex, nbGoroutine)
for i := 0; i < nbGoroutine; i++ {
locks[i].Lock()
}
for i := 0; i < 10; i++ {
go func(order int) {
for {
locks[order].Lock()
fmt.Printf("order%d\n", order)
time.Sleep(time.Millisecond * 500)
next := (order + 1) % nbGoroutine
locks[next].Unlock()
}
}(i)
}
locks[0].Unlock()
fmt.Scanf("\n")
}