基于channel实现的,两个协程交替打印出1-100
package mainimport ("fmt""sync")var (toOdd = make(chan struct{})toEven = make(chan struct{})wg = sync.WaitGroup{})func main() {wg.Add(2)go printOdd()go printEven()wg.Wait()fmt.Println("-----done-----")}func printOdd() {defer wg.Done()for i := 1; i <= 100; i += 2 {if i != 1 {<-toOdd}fmt.Println(i)toEven <- struct{}{}}}func printEven() {defer wg.Done()for i := 2; i <= 100; i += 2 {<-toEvenfmt.Println(i)if i != 100 {toOdd <- struct{}{}}}}