go 实现两个协程交替打印1-100的奇偶数 func main() { var c = make(chan struct{}) go func() { for i := 1; i <= 100; i++ { c<- struct{}{} if i%2 == 0 { fmt.Println(i) } } }() go func() { for i := 1; i <= 100; i++ { <-c if i%2 != 0 { fmt.Pri...
}funcprintEven(){deferwg.Done()fori :=2; i <=100; i +=2{ <-toEven fmt.Println(i)ifi !=100{ toOdd <-struct{}{} } } }
golang两个协程交替打印1-100的奇数偶数 golang两个协程交替打印1-100的奇数偶数 解法1: 两个管道实现 奇偶携程各自的管道,在收到通知后输出,然后通过对方管道通知对方输出 funcmain(){ ch0 :=make(chanint) ch1 :=make(chanint)gofunc(){fori :=1; i <10; i +=2{ <-ch0 fmt.Println(i) ch1 <...
golang两个协程交替打印出1-100基于channel实现的,两个协程交替打印出1-100 package main import ("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--...