通道(channel)是Golang中协程之间通信的重要方式
协程
- Golang中的协程和其它语言中定义的协程不太一样,Golang中的协程更倾向于并行;
协程之间的通信
package main
import (
"fmt"
"time"
)
func channelWrite(ch chan int){
ch<-5//写入数据
fmt.Println("I've written it.")//写入以后阻塞,直到被读出以后才能执行打印语句
}
func channelRead(ch chan int){
time.Sleep(3*1e9)
fmt.Println("Read from a channel",<-ch)//读取数据以后才能解除阻塞
}
func main(){
ch:=make(chan int)
go channelWrite(ch)
go channelRead(ch)
time.Sleep(5*1e9)
}
package main
import (
"fmt"
"time"
)
func channelWrite(ch chan int){
ch<-5//写入数据
fmt.Println("I've written it.")//缓冲区未满,因此直接执行打印语句
}
func channelRead(ch chan int){
time.Sleep(3*1e9)
fmt.Println("Read from a channel",<-ch)//缓冲区未满,无法阻塞
}
func main(){
ch:=make(chan in,5)//指定缓冲size=5
go channelWrite(ch)
go channelRead(ch)
time.Sleep(5*1e9)
}
协程的关闭:
if v,ok:=<-ch;ok{
...
}
协程的切换/选择:
func writeChan1(ch1 chan int){
for i:=0;i<100;i++ {
ch1 <-i
}
}
func writeChan2(ch2 chan int){
for i:=0;i<100;i++ {
ch2 <-i
}
}
func selectFunc(ch1,ch2 chan int){
for{
select{
case val:=<-ch1:
fmt.Printf("Got %v from channel 1\n",val)
case val:=<-ch2:
fmt.Printf("Got %v from channel 2\n",val)
}
}
}
func main(){
ch1:=make(chan int)
ch2:=make(chan int)
defer close(ch1)
defer close(ch2)
go writeChan1(ch1)
go writeChan2(ch2)
go selectFunc(ch1,ch2)
time.Sleep(1e9)
}