1. It is advisable to define the channel in the main goroutine and prepare the initial data, and then emit the sub-goroutine to implement the specific processing logic, each sub-goroutine can receive data from the channel and/or send data to the channel.
2. If it is not a special need, do not define unbuffered channal and do not receive or send data from the channel in the main goroutine.
3. In principle, the channel is actively closed by the sender, and the receiver is informed by the shadow variable whether the channel is closed.
4. Try to use a non-blocking select poll, which means that the SELECT statement block contains a default branch. A non-blocking select simply says that the SELECT statement block will not be blocked, that any case receiving or sending data from the channel can be blocked, and that any time a branch is blocked, go to the default branch. In order to poll several channel multiple times, a non-blocking select can be invoked using a For Loop loop.
5. If the non-blocking SELECT statement block acts on the unbuffered channel, the goroutine will be removed directly from the default branch because the channel is blocked. It is recommended to use buffered channel and capacity is large enough.
6. A non-blocking select is preferable to a timeout implementation. If necessary, you can call time for the time package. Newtimer (n * time. Second). C returns a channel with an absolute expiry time, and the channel contains an absolute expiry time value.
7. If you need a similar callback function, you can define struct a, which is nested a channel called Resultchan, the requester goroutinea send a to a channel called Messagechan, processing party goroutineb from Messagechan Receive A, and then send the result to Resultchan,goroutinea from Resultchan to receive the final result and then process, complete the callback.
Compare common code for non-blocking read data:
Achannel: = Make (chan int, 3)
go func () {do
: for
{ //For loop can continuously read data from Achannel, know timeout
Select { Case
E, OK: = <-achannel: //Shadow variable determines if the channel is closed if
OK {
FMT. PRINTLN ("Receive a value", E)
//Handlereceivedvalue (e)
} else {
fmt. Println ("Channel had been closed.")
Break done //exits the entire for loop
} case
<-time. Newtimer (5 * time. Second). C://Call the official timeout in time packet implementation, the code is very concise
fmt. Println ("Timeout") Break done
default: //The default branch guarantees that the SELECT statement is not blocked by the
FMT. PRINTLN ("No case fired, go Default")}}}
()