GO语言:goroutine同步与通道

80 阅读1分钟
package main

import (
	"fmt"
	"time"
)

//函数worker接收一个接收bool消息的通道的参数
func worker(done chan bool) {
	fmt.Println("start")
	time.Sleep(time.Second * 10)
	fmt.Println("end")

	done <- true //返回数据,结束了

}

func main() {
	done := make(chan bool, 1)
	go worker(done)
	<-done //锁住,直到函数worker结束返回结果
	fmt.Println("game over")
}
chan string代表:该通道既能接收消息,也能发出消息
chan <- string代表:该通道只能接收消息
<- chan string代表:该通道只能发出消息

package main

import (
	"fmt"
)

func gogo(sendStrings chan <- string, msg string) {
	sendStrings <- msg
}

func comego(sendStrings <- chan string, recvStrings chan <- string){
	msg := <-sendStrings
	recvStrings <- msg
}

func main() {
	gogos := make(chan string, 1)
	comegos := make(chan string, 1)

	gogo(gogos, "TOM")
	comego(gogos, comegos)

	fmt.Println(<-comegos)

}