0
0
Goprogramming~20 mins

Select with multiple channels in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Go Select Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of select with two channels
What is the output of this Go program?
Go
package main

import (
	"fmt"
	"time"
)

func main() {
	ch1 := make(chan string)
	ch2 := make(chan string)

	go func() {
		time.Sleep(100 * time.Millisecond)
		ch1 <- "channel 1"
	}()

	go func() {
		time.Sleep(50 * time.Millisecond)
		ch2 <- "channel 2"
	}()

	select {
	case msg1 := <-ch1:
		fmt.Println(msg1)
	case msg2 := <-ch2:
		fmt.Println(msg2)
	}
}
Achannel 2\nchannel 1
Bchannel 1
Cchannel 1\nchannel 2
Dchannel 2
Attempts:
2 left
💡 Hint
Remember that select picks the first channel ready to send or receive.
Predict Output
intermediate
2:00remaining
Select with default case output
What will this Go program print?
Go
package main

import "fmt"

func main() {
	ch := make(chan int)

	select {
	case val := <-ch:
		fmt.Println(val)
	default:
		fmt.Println("no value received")
	}
}
Ano value received
B0
Cdeadlock
Druntime error
Attempts:
2 left
💡 Hint
The channel is empty and no goroutine sends to it.
🔧 Debug
advanced
2:00remaining
Why does this select cause deadlock?
This Go program causes a deadlock. Why?
Go
package main

func main() {
	ch1 := make(chan int)
	ch2 := make(chan int)

	select {
	case <-ch1:
		// do nothing
	case <-ch2:
		// do nothing
	}
}
AThe select statement syntax is incorrect and causes compile error.
BBoth channels are unbuffered and no goroutine sends to them, so select blocks forever causing deadlock.
CThe channels are closed, so select panics at runtime.
DThe program runs fine and prints nothing.
Attempts:
2 left
💡 Hint
Think about what happens when select waits on channels with no senders.
Predict Output
advanced
2:00remaining
Select with multiple ready channels
What output does this Go program produce?
Go
package main

import (
	"fmt"
)

func main() {
	ch1 := make(chan string, 1)
	ch2 := make(chan string, 1)

	ch1 <- "first"
	ch2 <- "second"

	select {
	case msg := <-ch1:
		fmt.Println(msg)
	case msg := <-ch2:
		fmt.Println(msg)
	}
}
Afirst\nsecond
Bsecond
Cfirst
Dsecond\nfirst
Attempts:
2 left
💡 Hint
When multiple channels are ready, select picks one at random but Go's implementation picks the first case in source order.
Predict Output
expert
2:00remaining
Select with timeout using time.After
What is the output of this Go program?
Go
package main

import (
	"fmt"
	"time"
)

func main() {
	ch := make(chan string)

	select {
	case msg := <-ch:
		fmt.Println(msg)
	case <-time.After(100 * time.Millisecond):
		fmt.Println("timeout")
	}
}
Atimeout
Bruntime error
Cdeadlock
Dempty string
Attempts:
2 left
💡 Hint
The channel ch never receives a value, but time.After sends a value after 100ms.