Consider the following Go program that launches goroutines to print numbers. What will it print?
package main import ( "fmt" "time" ) func main() { for i := 0; i < 3; i++ { go func(i int) { fmt.Print(i, " ") }(i) } time.Sleep(100 * time.Millisecond) }
Think about when the goroutines capture the variable i.
The goroutines capture the variable i by reference, not by value. By the time they run, the loop has finished and i is 3, so all print 3.
Examine this Go program that uses channels to communicate between goroutines. What is printed?
package main import "fmt" func main() { ch := make(chan int, 2) ch <- 1 ch <- 2 fmt.Println(<-ch) fmt.Println(<-ch) }
Think about how buffered channels work and the order of sends and receives.
The channel has a buffer size of 2, so both sends succeed immediately. The receives happen in the same order, so it prints 1 then 2.
Look at this Go program. Why does it cause a deadlock at runtime?
package main func main() { ch := make(chan int) ch <- 5 <-ch }
Think about how unbuffered channels block on send and receive.
An unbuffered channel blocks the sender until a receiver is ready. Here, the send happens in main goroutine but no other goroutine receives, so it deadlocks.
Consider this Go program using select to receive from two channels. What will it print?
package main import ( "fmt" "time" ) func main() { ch1 := make(chan string) ch2 := make(chan string) go func() { time.Sleep(50 * time.Millisecond) ch1 <- "first" }() go func() { time.Sleep(10 * time.Millisecond) ch2 <- "second" }() select { case msg1 := <-ch1: fmt.Println(msg1) case msg2 := <-ch2: fmt.Println(msg2) } }
Which channel sends first? select picks a ready channel.
The goroutine sending "second" sleeps less, so ch2 is ready first. The select receives from ch2 and prints "second".
Why do Go programmers use the context package when working with concurrent operations?
Think about how to stop or control multiple goroutines working on the same task.
The context package helps control cancellation signals, deadlines, and passing values safely between goroutines, improving coordination.