Golang:对Chanels的理解

/ Golang / 没有评论 / 1525浏览

题目:使用两个goroutine交替打印序列,一个goroutine打印数字,一个打印字母,最终效果如下:12AB34CD56EF78GH910IJ

package main

import (
	"fmt"
	"runtime"
)

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	chan_n := make(chan bool)
	chan_c := make(chan bool,1)
	done := make(chan struct{})

	go func() {
		for i := 1; i<11; i+=2{
			<- chan_c //2 阻塞, 1解除2的阻塞,5解除2的阻塞
			fmt.Print(i) //输出
			fmt.Print(i+1)//输出
			chan_n <- true  // 4阻塞
		}
	}()

	go func() {
		char_seq := []string{"A","B","C","D","E","F","G","H","I","J","K"}
		for i:=0;i<10;i+=2{
			<-chan_n  //3 阻塞 ,4解除3的阻塞
			fmt.Print(char_seq[i]) //输出
			fmt.Print(char_seq[i+1])//输出
			chan_c <- true //5 阻塞
		}
		done <- struct{}{}
	}()

	chan_c <- true   //1 阻塞
	<- done
}