0
0
Goprogramming~20 mins

Channel synchronization in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Channel Synchronization 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 using channels?

Consider this Go program that uses a channel to synchronize goroutines. What will it print?

Go
package main

import (
	"fmt"
)

func main() {
	ch := make(chan string)
	go func() {
		ch <- "hello"
	}()
	msg := <-ch
	fmt.Println(msg)
}
Ahello
BCompilation error
CDeadlock detected at runtime
DEmpty line printed
Attempts:
2 left
💡 Hint

Think about how the channel is used to pass data between goroutines.

Predict Output
intermediate
2:00remaining
What happens if you read from a closed channel?

What will this Go program print?

Go
package main

import (
	"fmt"
)

func main() {
	ch := make(chan int)
	go func() {
		ch <- 42
		close(ch)
	}()
	val, ok := <-ch
	fmt.Println(val, ok)
	val, ok = <-ch
	fmt.Println(val, ok)
}
A
42 true
42 true
B
42 true
0 false
CCompilation error
DDeadlock at runtime
Attempts:
2 left
💡 Hint

Remember what happens when you read from a closed channel in Go.

🔧 Debug
advanced
2:00remaining
Why does this Go program deadlock?

Examine this Go program. It deadlocks at runtime. Why?

Go
package main

func main() {
	ch := make(chan int)
	ch <- 1
	<-ch
}
ABecause the channel is nil
BBecause the channel is closed before sending
CBecause the channel is unbuffered and no goroutine is receiving when sending
DBecause the channel is buffered but full
Attempts:
2 left
💡 Hint

Think about how unbuffered channels block on send and receive.

📝 Syntax
advanced
2:00remaining
Which option correctly creates a buffered channel of size 3?

Choose the correct Go code to create a buffered channel of integers with capacity 3.

Ach := make(chan int[3])
Bch := make(chan int)
Cch := make(chan int, "3")
Dch := make(chan int, 3)
Attempts:
2 left
💡 Hint

Recall the syntax of make for buffered channels.

🚀 Application
expert
2:00remaining
How many items are in the channel after this code runs?

Given this Go code, how many items remain in the channel after execution?

Go
package main

import (
	"fmt"
)

func main() {
	ch := make(chan int, 5)
	for i := 0; i < 3; i++ {
		ch <- i
	}
	<-ch
	ch <- 10
	fmt.Println(len(ch))
}
A4
B3
C2
D5
Attempts:
2 left
💡 Hint

Count how many sends and receives happen on the buffered channel.