[GO]channel实现同步

goroutine运行在相同的地址空间,因此访问共享内存必须 做好同步。goroutine奉行通过通信来共享内存,而不是共享内存通信

它跟map一样,使用make来创建,它是一个引用 ,而不是值传递

make(chan Type, capacity)

channel <- value //发送value到channel

<- channel  //接收并将其丢弃

x := <-channel  //从channel中接收数据,并赋值给x

x, ok := <-channel //功能同上,同时检查通道是否已关闭或者是否为空

package main

import (
    "fmt"
    //"time"
)

var ch = make(chan int)

func Printer(s string)  {
    for _, data := range s {
        //fmt.Println(string(data))
        fmt.Printf("%c", data)
        //time.Sleep(time.Second)
    }
}
//person1执行完成后才能到person2执行
func person1()  {
    Printer("hello")
    ch <- 666//给管道定数据,发送,放在了打印的后面
}

func person2()  {
    <- ch //从管道取数据,接收 ,如果通道没有数据他就会阻塞,放在了打印的前面
    Printer("world")
}

func main() {
    go person1()
    go person2()
    for true {
    }
}

先看执行的结果

helloworld

如何实现的?

首先需要知道的是person1和person2的子协程几乎是同时执行的,但是,因为person2在打印之前有一个管道的处理,而与几乎同时,person1已经在执行print语句了,执行完print语句后又向管道存了值

person2中的管道语句一看管道来值了,也就继续执行了后面的print语句,这样才实现了上面的结果

原文地址:https://www.cnblogs.com/baylorqu/p/9672786.html