一、基本输入输出
- 普通阻塞
- 容量管道
- 阻塞异步操作工作任务,基础控制阻塞模式:通过开关来引起阻塞
- 发送和接收,模拟消息
二、select的使用
- 获取异步信息,异步发送, for-select-case 挂起等待读取数据
- 超时,一个超时一个不超时的例子,使用time.After设置超时执行
- select-default跳出阻塞
三、close的使用
- close关闭写入,允许读取。close+more && for-if && 开关,读取所有chan值。
四、定时器
- 定时器,控制chan阻止阻塞发生,这样就不会走gorun
- 延时器
package main
import (
"fmt"
"time"
)
func worker(done chan bool) {
fmt.Println("working...")
time.Sleep(time.Second)
fmt.Println("done")
done <- true
}
func ping(pings chan<- string, msg string) {
pings <- msg
}
func pong(pings <-chan string, pongs chan<- string) {
msg := <-pings
pongs <- msg
}
func main() {
message := make(chan string)
go func() { message <- "ping" }()
msg := <-message
fmt.Println(msg)
msg2 := make(chan string, 2)
msg2 <- "buffered"
msg2 <- "channel"
fmt.Println(<-msg2)
fmt.Println(<-msg2)
done := make(chan bool, 1)
go worker(done)
<-done
pings := make(chan string, 1)
pongs := make(chan string, 1)
ping(pings, "hello chan")
pong(pings, pongs)
fmt.Println(<-pongs)
c1 := make(chan string)
c2 := make(chan string)
go func() {
time.Sleep(2 * time.Second)
c1 <- "hello11"
c1 <- "hello22"
}()
go func() {
time.Sleep(1 * time.Second)
c2 <- "world"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-c1:
fmt.Println("received1", msg1)
case msg2 := <-c2:
fmt.Println("received2", msg2)
}
}
fmt.Println("received1 out", <-c1)
c3 := make(chan string)
go func() {
time.Sleep(2 * time.Second)
c3 <- "result 1"
}()
select {
case res := <-c3:
fmt.Println(res)
case <-time.After(1 * time.Second):
fmt.Println("timeout 1")
}
msg5 := make(chan string, 1)
signals := make(chan string, 1)
select {
case msg := <-msg5:
fmt.Println(msg)
default:
fmt.Println("no msg received")
}
msgStr1 := "hi"
select {
case msg5 <- msgStr1:
fmt.Println("sent message", msgStr1)
default:
fmt.Println("no meg sent")
}
select {
case msg := <-msg5:
fmt.Println("receive msg", msg)
case sig := <-signals:
fmt.Println("receive signal", sig)
default:
fmt.Println("no activity")
}
jobs := make(chan int, 5)
done2 := make(chan bool)
go func() {
for {
j, more := <-jobs
if more {
fmt.Println("received job", j)
} else {
fmt.Println("receive all jobs")
done2 <- true
return
}
}
}()
for i := 0; i < 3; i++ {
jobs <- i
fmt.Println("sent job", i)
}
close(jobs)
fmt.Println("sent all jobs")
<-done2
timer := time.NewTimer(2 * time.Second)
<-timer.C
fmt.Println("Time. 1 fired")
timer2 := time.NewTimer(time.Second)
go func() {
<-timer2.C
fmt.Println("timer2 2 fired")
}()
stop2 := timer2.Stop()
if stop2 {
fmt.Println("t2 stop", stop2)
}
time.Sleep(2 * time.Second)
ticker := time.NewTicker(500 * time.Microsecond)
done4 := make(chan bool)
go func() {
for {
select {
case <-done4:
return
case t := <-ticker.C:
fmt.Println("tick at", t)
}
}
}()
time.Sleep(50 * time.Millisecond)
ticker.Stop()
done4 <- true
fmt.Println("ticker stopped")
}