Go协程实现通道传值

77 阅读1分钟

代码:

package main
import(
	"fmt"
	"time"
)

func Goroutine1(ch chan string){
	fmt.Println("start goroutine1")
	ch <-"goroutine2"
	data := <-ch
	fmt.Printf("goroutine1 get channel:%v\n",data)
	ch <-"Main goroutine"
}

func Goroutine2(ch chan string){
	fmt.Println("start goroutine2")
	data := <-ch
	fmt.Printf("goroutine2 get channel:%v\n",data)
	ch <-"goroutine1"
}

/*main函数中调用*/
func main(){
	//构建通道
	ch := make(chan string)
	//执行并发
	go Goroutine1(ch)
	//执行并发
	go Goroutine2(ch)

	//延迟5秒,使用Goroutine1()和Goroutine2()相互读写通道数据
	time.Sleep(5 * time.Second)

	//读取Goroutine1()写入的数据
	data := <- ch
	fmt.Printf("main goroutine get channel:%v\n",data)

}

输出:

start goroutine2
start goroutine1
goroutine2 get channel:goroutine2
goroutine1 get channel:goroutine1
main goroutine get channel:Main goroutine

说明:

1.go中用make默认创建双向通道(可写可读)用于两个或两个以上协程之间的通信,可创建无缓冲通道和带缓冲通道,本例中创建的为无缓冲通道,带缓冲通道需要设置通道元素数量参数。

2.无缓冲通道必须先写入才可以读取,否则程序将等待直到写入成功才读取。

3.被成功读取的元素将在通道中消失,一写一读交替进行。本例Goroutine1和Goroutine2中最后剩余的元素为"Main goroutine",其他通道数据已经被成功读取。