5.10 go通过channel实现同步

/**
 两人同时打印,竞争资源;通过channel实现同步
*/

package main
import (
	"fmt"
	"time"
)
//全局变量 创建一个channel
var ch=make(chan int)
func Printer(str string){
	for _,data:=range str{
		fmt.Printf("%c",data)
		time.Sleep(time.Second)
	}
	
	
}
func person1(){
	Printer("hello")
	//往管道发送数据
	ch<-77
}
func person2(){
	//从管道接收数据,如果没有数据就会阻塞
	<-ch
	Printer("world")
}

func main(){
	//新建两个协程,代表两个人去打印,2个人同时使用打印机
	go person1()
	go person2()
	
	for{}
	
	
	
}
发布了134 篇原创文章 · 获赞 104 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/h4241778/article/details/105374318