fun + go channel = funnel
Just a series of exercises in understanding go concurrency.
- Goroutines are concurrently executing functions (within the same address space)
- Because goroutines run in the same address space, they can refer to variables with common scope
- One approach to safe concurrency is to use a 'mutex' (mutual exclusion lock)
- The main function of a Go program runs in a goroutine (running programs always have at least one goroutine)
- When the 'main' goroutine exits, the entire process exits (along with any unfinished goroutines)
- The Go scheduler decides which goroutine(s) runs at any given moment, but they are limited in how they transition from one goroutine to another
- When a goroutine encounters a blocking operation the scheduler is given the opportunity to transition to a different goroutine
- When no goroutine can proceed a deadlock occurs (which results in a panic)
- When multiple goroutines attempt to access the same variable and at least one access is a 'write' operation, there is a potential for a data race, which could result in crashes or memory corruption
- Another approach to safe concurrency is Go channels, which are FIFO queue structures that are actually safe to send to/receive from across multiple goroutines
- Go Slogan: "Do not communicate by sharing memory; instead, share memory by communicating."
- Attempting to receive on an empty channel blocks the current goroutine until a value is sent or the channel is closed (which results in the 'zero value' being received).
- Attempting to send on an 'unbuffered' channel blocks until the value is received or the channel is closed (which then results in a panic)
- Concurrency != Parallelism
- A Go program that is limited to running a single goroutine at a time is said to be concurrent
- A Go program that can run multiple goroutines at the same time (such as by multiple CPUs) is said to be parallel
- A function that loads a channel should almost always close it when finished (ie.
defer close(ch)
)
- The 'go' Statement: https://go.dev/ref/spec#Go_statements
- Channel Types: https://go.dev/ref/spec#Channel_types
- Race Detector: https://go.dev/doc/articles/race_detector
- Concurrency: https://go.dev/doc/effective_go#concurrency
- Concurrency Patterns - Pipelines: https://go.dev/blog/pipelines
- Concurrency Patterns - Context: https://go.dev/blog/context
- Concurrency Patterns - Timing out, moving on: https://go.dev/blog/concurrency-timeouts (probably obsolete since advent of 'context')
- Advanced Concurrency Patterns: https://go.dev/blog/io2013-talk-concurrency
- Concurrency is not Parallelism: https://go.dev/blog/waza-talk
- Channel Axioms: https://dave.cheney.net/2014/03/19/channel-axioms
- Visualizing Go Concurrency: https://divan.dev/posts/go_concurrency_visualize/