chan相关知识
代码片段一—chan用于两个goruntime之间通信
源代码
package main
import "fmt"
import "time"
var strChan = make(chan string,3)
func main(){
syncChan1 := make(chan struct{},1)
syncChan2 := make(chan struct{},2)
go func(){
<- syncChan1
fmt.Println("[receiver] Received a sync signal and wait a second...")
time.Sleep(time.Second)
for{
if elem,ok := <-strChan;ok{
fmt.Println("[receiver] Received:",elem)
}else{
break
}
}
fmt.Println("[receiver] Stopped.")
syncChan2 <- struct{}{}
}()
go func(){
for i,elem := range []string{
"a","b","c","d"}{
fmt.Println("[sender] Sent:",elem)
strChan <- elem
if (i+1)%3==0 {
syncChan1 <- struct{}{}
fmt.Println("[sender] Sent a sync signal. wait 1 secnd...")
time.Sleep(time.Second)
}
}
fmt.Println("[sender] wait 2 seconds...")
time.Sleep(time.Second)
close(strChan)
syncChan2 <- struct{}{}
}()
fmt.Println("[main] waiting...")
<- syncChan2
<- syncChan2
fmt.Println("[main] stoped")
}
运行结果
[main] waiting...
[sender] Sent: a
[sender] Sent: b
[sender] Sent: c
[sender] Sent a sync signal. wait 1 secnd...
[receiver] Received a sync signal and wait a second.