0
0
Goprogramming~20 mins

Blocking behavior in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Go Blocking Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Go program with channels?
Consider the following Go code. What will it print when run?
Go
package main
import (
	"fmt"
)
func main() {
	ch := make(chan int)
	go func() {
		ch <- 42
	}()
	val := <-ch
	fmt.Println(val)
}
A42
B0
CCompilation error
DDeadlock panic
Attempts:
2 left
💡 Hint
Think about how channels block until data is sent or received.
Predict Output
intermediate
2:00remaining
What happens when reading from a closed channel?
What will this Go program print?
Go
package main
import "fmt"
func main() {
	ch := make(chan int)
	close(ch)
	val, ok := <-ch
	fmt.Println(val, ok)
}
A0 true
B0 false
CCompilation error
DDeadlock panic
Attempts:
2 left
💡 Hint
Reading from a closed channel returns zero value and false.
Predict Output
advanced
2:00remaining
What is the output of this select with blocking channels?
Analyze the following Go code and determine its output.
Go
package main
import (
	"fmt"
	"time"
)
func main() {
	ch1 := make(chan string)
	ch2 := make(chan string)
	go func() {
		time.Sleep(100 * time.Millisecond)
		ch1 <- "first"
	}()
	go func() {
		time.Sleep(50 * time.Millisecond)
		ch2 <- "second"
	}()
	select {
	case msg1 := <-ch1:
		fmt.Println(msg1)
	case msg2 := <-ch2:
		fmt.Println(msg2)
	}
}
Afirst
BCompilation error
Csecond
DDeadlock panic
Attempts:
2 left
💡 Hint
Which channel sends first after the sleep?
Predict Output
advanced
2:00remaining
What error does this Go program produce?
What happens when you run this Go code?
Go
package main
func main() {
	ch := make(chan int)
	ch <- 1
}
ADeadlock panic
BCompilation error
CProgram prints 1
DNo output, program exits normally
Attempts:
2 left
💡 Hint
Sending on an unbuffered channel blocks until another goroutine receives.
🧠 Conceptual
expert
2:00remaining
How many items are in the buffered channel after this code runs?
Given the following Go code, how many items remain in the channel after execution?
Go
package main
import "fmt"
func main() {
	ch := make(chan int, 3)
	ch <- 10
	ch <- 20
	<-ch
	ch <- 30
	fmt.Println(len(ch))
}
A3
B0
C1
D2
Attempts:
2 left
💡 Hint
Remember that reading from the channel removes an item.