/**
两人同时打印,竞争资源;通过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{}
}
5.10 go通过channel实现同步
猜你喜欢
转载自blog.csdn.net/h4241778/article/details/105374318
今日推荐
周排行