Checkpoint 3
Concurrency mixed with what came before: goroutines, channels, locks, context and the basics they lean on.
main runs go fmt.Println("hi") and then returns straight away. What happens?
All questions with explanations (answers shown)
1.
mainrunsgo fmt.Println("hi")and then returns straight away. What happens?Answer: Most likely nothing prints, because the program exits when
mainreturnsThe program ends as soon as
mainreturns and does not wait for other goroutines. Use async.WaitGroupor a channel to wait.2.
ch := make(chan int), thench <- 1inmainwith no other goroutines. What happens?Answer:
fatal error: all goroutines are asleep - deadlock!A send on an unbuffered channel waits for a receiver. No goroutine can ever receive, so the runtime notices and stops the program.
3.
ch := make(chan int, 1); ch <- 7; close(ch); a := <-ch; b, ok := <-ch. What area,bandok?Answer:
7 0 falseClosing does not throw away buffered values, so
agets 7. After that the channel is empty and closed, so receives give the zero value andokis false.4. Which command reports data races while your tests run?
Answer:
go test -raceThe race detector is built in when you pass
-race. It only sees races that actually happen during the run, so tests need to exercise the concurrent paths.5. After
ctx, cancel := context.WithCancel(parent)andcancel(), what doesctx.Err()return?Answer:
context.CanceledOnce a context is done,
Errsays why. A manual cancel givescontext.Canceled; a passed deadline or timeout givescontext.DeadlineExceeded.6. Why call
wg.Add(1)before thegostatement instead of inside the new goroutine?Answer:
Waitcould run before the goroutine callsAdd, see a zero counter and return earlyWaitreturns when the counter is zero. If the goroutine has not started yet, the counter may still be zero. Adding first removes that race.7.
chis an empty channel. What doesselect { case v := <-ch: fmt.Print(v); default: fmt.Print("none") }do?Answer: Prints
noneright awayA
selectwith adefaultnever blocks. If no case is ready at that moment,defaultruns.8. Several goroutines write to the same plain
mapwith no lock. What can happen?Answer: The program can crash with
fatal error: concurrent map writesBuilt-in maps are not safe for concurrent writes, and the runtime crashes the program when it catches it. Guard the map with a
sync.Mutex, or usesync.Mapfor the cases it fits.9. What does
mu.Lock(); defer mu.Unlock()at the top of a function give you?Answer: The lock is released when the function returns, including early returns and panics
Deferred calls run when the surrounding function returns, however it returns. That is why the unlock sits right next to the lock.
10. On Go 1.22 or later,
for i := 0; i < 3; i++ { wg.Add(1); go func() { defer wg.Done(); fmt.Print(i) }() }followed bywg.Wait(). What prints?Answer: Each of 0, 1 and 2 once, in any order
Since Go 1.22 every loop iteration gets its own
i, so each goroutine sees a different value. The scheduler decides who runs first, so the order is not fixed.