Aims to learn the knowledge about concurrency in Go
1-echo-text | ||
2-compress-file | ||
basics | ||
exercise | ||
README.md |
go-concurrency
Aims to learn the knowledge about concurrency in Go
Flow control with channels
-
We can imagine that channel is a pipe,
chan<-
means to send a value into the channel.<-chan
means to receive a value from the channel. -
select ... case
can execute sending value into a channel
Range and Close
- 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.
v, ok := <-ch
,ok
isfalse
if there are no more values to receive and the channel is closed. - The loop for
i:= range c
receives values from the channel repeatedly until it 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.
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
Default selection
- The
default
case in aselect
is run if no other case is ready. - Use a
default
case to try a send or receive without blocking
select {
case i:= <-c:
// use i
default:
// receive when c is blocked
}
sync.Mutex
Channels are great for communication, but what if we don't need communication?
What if we just want to make sure only one goroutine can access a variable at a time to avoid conflicts? This concept is called mutual exclusion
, and the conventional name for the data structure that provides it is mutex
Go's standard library provides mutual exclusion with sync.Mutex
and its two methods: Lock
and Unlock