Channels Flashcards
Into what a CPU is splitted?
CPU is split into CORES
Which keyword is used to spawn a new goroutine?
go “name of the function”
e.g.
go doSomething()
What are channels?
Channels are a typed, thread-safe queue.
What the job of channels?
Channels allow different goroutines to communicate with each other.
How to create a channel without a buffer?
ch := make(chan int)
How to send data to a channel?
Use the arrow <-
notation
ch <- 69
This operation will block until another goroutine is ready to receive the value.
How to receive data from a channel?
v := <-ch
This reads and removes a value from the channel and saves it into the variable v.
What is a deadlock?
A deadlock is when a group of goroutines are all blocking so none of them can continue.
TIP: This is a common bug that you need to watch out for in concurrent programming.
How to create a channel with a buffer?
ch := make(chan int, 100)
What happens on a buffered channel?
- Sending blocks when the buffer is full
- Receiving blocks only when the buffer is empty
How to close a channel?
close(ch)
How to check if a channel is closed?
v, ok := <-ch
ok is false if the channel is empty and closed.
What will happen if we send data to a closed channel?
PANIC
Can we leave the channels open?
YES!
There’s nothing wrong with leaving channels open, they’ll still be garbage collected if they’re unused.