1. Start a writeData coroutine and write 50 integers to the pipeline intChan
2. Start a readData coroutine to read the data written by writeData from the pipeline intChan
Note: read and write operations are data in the same pipeline, the main thread needs to wait for the completion of the read and write coroutine before exiting
package main
import "fmt"
// 写入
func write(intChan chan int) {
for i := 0; i <= 50; i++ {
intChan <- i
}
close(intChan)
}
// 读出
func read(intChan chan int, doneRead chan bool) {
for {
val, ok := <-intChan
if !ok {
break
}
fmt.Println("输出:", val)
}
doneRead <- true
}
func main() {
intChan := make(chan int)
doneRead := make(chan bool)
//写入50个整数
go write(intChan)
//读出数据
go read(intChan, doneRead)
//结束进程
<-doneRead
close(doneRead)
fmt.Println("输出结束")
return
}
Use defer anonymous function to capture panic
demo
defer func(){
if err:=recover();err!=nil{
fmt.Println("此方法有panic:",err)
}
}()
Place of application: Apply where you feel or feel that panic will occur
timer timing task
Method 1: timer:=time.NewTimer(定时时间)//timing time
t:= <-time.C//Automatically send data at the point
Method 2: t := <-time.After(定时时间)//Receive data at regular intervals
Summary: Method 2 is the encapsulation of Method 1, and the two are internally consistent
Timer pause and reset
Pause: timer.Stop()(Must use the method to determine the timed task)