15-golang并发中channel的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33781658/article/details/83785476

我们先写一段代码

func main() {
   go person1()
   go person2()

   for {

   }
}

func Printer(str string) {

   for _, ch := range str {
      fmt.Printf("%c", ch)
      time.Sleep(time.Second)
   }

   fmt.Println()

}

func person1() {
   Printer("hello")
}

func person2() {
   Printer("world")
}

这段代码很简单,就是模拟两个人使用1个打印机

那么现在是并发状态使用打印机

结果我们会发现

出现了whoerlllod这样并发打印的效果

然后我们需要想一个办法

使得我们的person1和person2有一个同步的状态

就是person1打印完成了再打印person2

这时候我们就需要使用到channel了

我们要定义一个成员变量

var channel = make(chan int)

func main() {
   go person1()
   go person2()

   for {

   }
}

func Printer(str string) {

   for _, ch := range str {
      fmt.Printf("%c", ch)
      time.Sleep(time.Second)
   }

   fmt.Println()

}

func person1() {
   Printer("hello")
   channel <- 1
}

func person2() {
   <-channel
   Printer("world")
}

这里的<-channel意思是

在channel收到数据之前,这里就是阻塞的

channel<- 1实际上就是发了一个1这个信息

这样person2中就收到了一个1

那么这里的子协程就不阻塞了,就可以进行打印了

所以channel就是通过传递信息这样的方式

来实现同步

当然数据也可以支持其他的格式

比如string

var channel = make(chan string)

func main() {
   go person1()
   go person2()

   for {

   }
}

func Printer(str string) {

   for _, ch := range str {
      fmt.Printf("%c", ch)
      time.Sleep(time.Second)
   }

   fmt.Println()

}

func person1() {
   Printer("hello")
   channel <- "ok"
}

func person2() {
   <-channel
   Printer("world")
}

猜你喜欢

转载自blog.csdn.net/qq_33781658/article/details/83785476