A sender can close a channel to indicate that no more values will be sent. Receivers can test whether a channel has been closed with a second parameter:
ok is false if there are no more values to receive and the channel is closed.
Only the sender should close a channel, never the receiver. Sending on a closed channel will cause a panic.
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.
Range
The loop for i := range c receives values from the channel repeatedly until it is closed.
Output is:
0
1
1
2
3
5
8
13
21
34
Select
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.
Go’s standard library provides mutual exclusion with sync.Mutex and its two methods Lock and Unlock.
Example:
We can define a block of code to be executed in mutual exclusion by surrounding it with a call to Lock and Unlock as shown on the Inc method.
We can also use defer to ensure the mutex will be unlocked as in the Value method.