Golang 通道控制并发 goroutine 2

代码示例:

package main

import (
	"fmt"
	"reflect"
	"time"
)

func Channel1(c chan string) {
	time.Sleep(time.Second * 3)
	fmt.Println("Enter Channel1!")
	c <- "ydook.com 1"
}

func Channel2(c chan string) {
	fmt.Println("Enter Channel2!")
	fmt.Println("Channel2 c = ", c)
	fmt.Println("Channel2 type c = ", reflect.TypeOf(c))

	time.Sleep(time.Second * 2)

	c <- "ydook.com 2"
}

func main() {

	c := make(chan string)
	fmt.Println("c = ", c)
	fmt.Println("type c = ", reflect.TypeOf(c))

	go Channel1(c)

	cmag1 := <-c
	fmt.Println("cmag1 = ", cmag1)
	fmt.Println("type cmag1 = ", reflect.TypeOf(cmag1))

	cb := make(chan string)
	fmt.Println("cb = ", cb)
	fmt.Println("type cb = ", reflect.TypeOf(cb))

	go Channel2(cb)
	fmt.Println("cb = ", cb)

	cmag2 := <-cb
	fmt.Println("cmag = ", cmag2)
	fmt.Println("type cmag2 = ", reflect.TypeOf(cmag2))

}

运行结果:

Enter Channel1!
cmag1 =  ydook.com 1
type cmag1 =  string
cb =  0xc0000180c0
type cb =  chan string
cb =  0xc0000180c0
Enter Channel2!
Channel2 c =  0xc0000180c0
Channel2 type c =  chan string
cmag =  ydook.com 2
type cmag2 =  string



上一篇:【Shader】解读Unity Chan的卡通材质


下一篇:关于golang select的用法