40 lines
734 B
Go
40 lines
734 B
Go
package main
|
||
|
||
import (
|
||
"fmt"
|
||
"sync"
|
||
)
|
||
|
||
// 通道的声明
|
||
var c chan int //需要指定通道中元素的类型,引用类型,需要初始化
|
||
var wait sync.WaitGroup
|
||
|
||
func noBufferedChannel() {
|
||
c = make(chan int) //不带带缓冲区的通道初始化
|
||
wait.Add(1)
|
||
go func() {
|
||
defer wait.Done()
|
||
x := <-c //接受
|
||
fmt.Println("从通道C中取得值:", x)
|
||
}()
|
||
c <- 10 //发送
|
||
wait.Wait()
|
||
}
|
||
|
||
func bufferedChannel() {
|
||
c = make(chan int, 1) //带缓冲区的初始化
|
||
c <- 10
|
||
fmt.Println("10发送到通道中了")
|
||
x := <-c
|
||
fmt.Println("从通道C中取到值", x)
|
||
c <- 20
|
||
fmt.Println("20发送到通道中了")
|
||
z := <-c
|
||
fmt.Println("从通道C中取到值", z)
|
||
close(c)
|
||
}
|
||
|
||
func main() {
|
||
bufferedChannel()
|
||
}
|