Go - Concurrency
Concurrency is part of the language, not a library. 3 key concepts:
- goroutine: lightweight threads.
- channels: typed pipes used to communicate and synchronize between goroutines.
- select: control structure to coordinate concurrent operations.
What is goroutine?
A goroutine is a function or method that executes concurrently alongside any other goroutines using a special goroutine thread. Goroutine threads are more lightweight than standard threads, with most Golang programs using thousands of goroutines at once.
- to create a goroutine, add the
go
keyword before the function declaration.
What are Go channels?
Channels are used to transfer data between goroutines.
- a channel can transfer data of the same type.
- bidirectional.
Receivers always block until there is data to receive.
If the channel is unbuffered, the sender blocks until the receiver has received the value. If the channel has a buffer, the sender blocks only until the value has been copied to the buffer; if the buffer is full, this means waiting until some receiver has retrieved a value.
A buffered channel can be used like a semaphore, for instance to limit throughput.
A channel is created by chan
.
var channel_name chan Type
channel_name:= make(chan Type)
To send and received data:
- send data:
channel_name <- element
- receive data:
element := <-Mychannel
read vs write
chan
// read-write<-chan
// read onlychan<-
// write only
How to stop a gorountine?
To make a goroutine stoppable, let it listen a quit channel.
// Create a quit channel.
quit := make(chan bool)
go func() {
for {
select {
case <-quit:
return
default:
// ...
}
}
}()
// Send `true` to quit channel.
quit <- true
How to handle errors from goroutines?
errs := make(chan error, 1)
go func() {
errs <- foo()
}()
// ...
if err := <-errs; err != nil {
// handle error
}
Is Go following CSP model?
Yes, Go's concurrency model is heavily inspired by and based on the principles of Communicating Sequential Processes (CSP), a formal language for describing patterns of interaction in concurrent systems, primarily developed by Tony Hoare.
However, it's important to understand the nuance:
- Inspiration, Not Strict Implementation: Go isn't a strict, formal implementation of the mathematical CSP model. It's a practical programming language that takes the core ideas of CSP and implements them in a usable, efficient way.
- Key CSP Concepts in Go:
- Processes (Goroutines): Go's
goroutines
are lightweight, independently executing functions. They are analogous to the "sequential processes" in CSP. - Communication Channels (Channels): Go's
channels
provide synchronized, typed conduits through which goroutines can communicate by sending and receiving values. This directly maps to the concept of channels in CSP for message passing. - Choice/Alternation (
select
): Go'sselect
statement allows a goroutine to wait on communication operations across multiple channels, executing the one that becomes ready first. This is directly analogous to CSP's concept of choice or guarded commands based on communication readiness.
- Processes (Goroutines): Go's
- Go's Philosophy: Go strongly promotes the CSP style of concurrency with its famous mantra: "Do not communicate by sharing memory; instead, share memory by communicating." This emphasizes using channels for coordination and data transfer between goroutines rather than relying solely on traditional mutexes and shared state (though Go supports those too).
- Practical Differences/Extensions:
- Go channels can be buffered, allowing a degree of decoupling, whereas classic CSP often focuses on unbuffered (synchronous) communication.
- Go has the concept of closing channels.
- Go allows traditional shared-memory concurrency with mutexes (
sync
package), whereas pure CSP models often avoid shared state entirely. Go is pragmatic.
In summary: While not a mathematically pure CSP implementation, Go's concurrency primitives (goroutines, channels, select) are directly derived from the core ideas of CSP, making it one of the most prominent and successful examples of a language applying CSP principles in practice. When people talk about Go's concurrency, CSP is the underlying theoretical model they are usually referring to.