Skip to content

Concurrent

Advanced · Concurrency

A goroutine is a lightweight thread started with go f(). Goroutines communicate over channels (chan T) rather than shared memory, and sync.WaitGroup waits for a group to finish. This topic introduces the basics; channels, select, sync, context, and concurrency_patterns go deeper.

Print from goroutines and wait with a WaitGroup.

Show hint
We have multiple printers (though these may also be non-functional).
Our goal is to print something, but what exactly should be printed?

Source

Safely increment a counter from many goroutines.

Show hint
Updating a variable from multiple goroutines can lead to a data race. A data race occurs when multiple goroutines read and write the same variable simultaneously without proper synchronization.
Consider a counter as an example: concurrent updates can lead to unexpected results.
Learn more about mutexes to handle this issue: https://pkg.go.dev/sync#Mutex.

Source

Send values over a channel and receive them.

Show hint
Writing messages to closed channels will cause a panic.
To prevent panics, avoid sending messages to channels that have been closed.
Note: Channels can be iterated using `for-range` loops.

Source