【Go Concurrency】golang
一、A goroutine is a lightweight thread managed by the Go runtime.express
二、Channels are a typed conduit through which you can send and receive values with the channel operator, <-
.緩存
三、Like maps and slices, channels must be created before use:dom
By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.ide
四、Channel會緩存。oop
五、A sender can close
a channel to indicate that no more values will be sent. Receivers can test whether a channel has been closed by assigning a second parameter to the receive expression: afterui
ok
is false
if there are no more values to receive and the channel is closed.spa
The loop for i := range c
receives values from the channel repeatedly until it is closed.3d
Note: Only the sender should close a channel, never the receiver. Sending on a closed channel will cause a panic.code
Another note: Channels aren't like files; you don't usually need to close them. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a range
loop.
六、The select
statement lets a goroutine wait on multiple communication operations.
A select
blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.
七、The default
case in a select
is run if no other case is ready.
Use a default
case to try a send or receive without blocking: