The channel is not assigned to the data when it is blocked, you can use this mechanism to complete the monitoring of the event
WG: = new (sync. WAITGROUP) WG. ADD (2) Event: = Make (chan bool)//Function go func () {defer WG. Done () for I: = 0; I < 5; i++ {fmt. Println ("Before Trigger event", I)}event <-true//Trigger event} () go func () {<-eventdefer WG. Done () for I: = 0; I < 5; i++ {fmt. Println ("After triggering event", I)}} () WG. Wait ()
Output:
0 before triggering event
1 before triggering event
2 before triggering event
3 before triggering event
4 before triggering event
0 after triggering event
1 after triggering event
2 after triggering event
3 after triggering event
4 after triggering event
When using the channel, be aware that
If Chan's capacity is full, a deadlock will occur
Such as:
Data:=make (chan int, 3) Exit:=make (chan bool) data<-1data<-2data<-3data<-4//run here will be blocked because Chan capacity is full
Len returns the number of elements that have not been read in Chan, the cap returns the buffer size, close closes the current Chan
Judge Chan whether to close
for{if d,ok:=<-data;ok}{fmt. Println (d)}else{Break}}
One-way Chan: only responsible for receiving, or only responsible for sending
Equivalent to separating Chan's send and receive, turning it into two easy-to-control variables
c: = make (chan int, 3) var send chan<-int = c//send-onlyvar recv <-chan int = c//receive-onlysend <-1<-re Cv
Go's channel explanation