

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: Concurrency
incomplete
2: Channels
incomplete
3: Channels
incomplete
4: Buffered Channels
incomplete
5: Closing Channels in Go
incomplete
6: Range
incomplete
7: Select
incomplete
8: Select Default Case
incomplete
9: Channels Review
incomplete
10: Ping Pong
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Channels are a typed, thread-safe queue. Channels allow different goroutines to communicate with each other.
Like maps and slices, channels must be created before use. They also use the same make keyword:
ch := make(chan int)
ch <- 69
The <- operator is called the channel operator. Data flows in the direction of the arrow. This operation will block until another goroutine is ready to receive the value.
v := <-ch
This reads and removes a value from the channel and saves it into the variable v. This operation will block until there is a value in the channel to be read. Channels are First-In-First-Out (FIFO), meaning values are received in the same order they are sent.
Like maps and slices, channels are reference types. Changes made inside a function affect the original.
func send(ch chan int) {
ch <- 99
}
func main() {
ch := make(chan int)
go send(ch)
fmt.Println(<-ch) // 99
}
A deadlock is when a group of goroutines are all blocking so none of them can continue. This is a common bug that you need to watch out for in concurrent programming.
Run the program. You'll see that it deadlocks and never exits. The sendIsOld function is trying to send on a channel, but no other goroutines are running that can accept the value from the channel.
Fix the deadlock by spawning a goroutine to send the "is old" values.