Bird
Raised Fist0
Goprogramming~10 mins

Select with multiple channels in Go - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Select with multiple channels
Start
↓
Wait for any channel
↓
Chan1
↓
Handle
↓
Repeat or Exit
The program waits for messages from multiple channels and handles whichever is ready first, including a default case if none are ready.
Execution Sample
Go
package main
import "fmt"
func main() {
 c1 := make(chan string)
 c2 := make(chan string)
 select {
 case msg1 := <-c1:
  fmt.Println("Received", msg1)
 case msg2 := <-c2:
  fmt.Println("Received", msg2)
 default:
  fmt.Println("No message received")
 } 
}
This code waits to receive from two channels and prints the message received or a default message if none are ready.
Execution Table
StepSelect CaseChannel Ready?Action TakenOutput
1case msg1 := <-c1NoSkipped
2case msg2 := <-c2NoSkipped
3defaultN/AExecutedNo message received
4EndN/AProgram ends
💡 No channels were ready, so default case executed and program ended.
Variable Tracker
VariableStartAfter Select
msg1undefinedundefined
msg2undefinedundefined
Key Moments - 2 Insights
Why does the default case run even though channels exist?
Because neither channel had data ready to receive, so select immediately runs the default case as shown in execution_table row 3.
What happens if multiple channels are ready at the same time?
Select picks one at random to execute. This is not shown here but is important to know for concurrency.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, which step shows the default case running?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Check the 'Action Taken' and 'Output' columns in the execution_table.
At which step does the program decide no channels are ready?
AStep 3
BStep 4
CStep 1
DStep 2
💡 Hint
Look at the 'Channel Ready?' column and when default executes.
If c1 had a message ready, what would change in the execution table?
ADefault case would still run
BStep 1 would execute and print the message
CStep 2 would execute instead
DProgram would deadlock
💡 Hint
Refer to how select picks the first ready channel case to execute.
Concept Snapshot
select {
 case <-chan1:
  // handle chan1
 case <-chan2:
  // handle chan2
 default:
  // handle no ready channel
}

- Waits for multiple channels
- Executes first ready case
- Default runs if none ready
- Useful for concurrent waits
Full Transcript
This example shows how Go's select statement waits for multiple channels. It checks each channel to see if it has data ready. If none are ready, the default case runs immediately. The execution table shows each step: first checking channel 1, then channel 2, then default. Variables msg1 and msg2 remain undefined because no data was received. Key points include that default runs only if no channels are ready, and if multiple channels are ready, select picks one randomly. The quiz tests understanding of which step runs default and what happens if a channel is ready.

Practice

(1/5)
1.

What does the select statement do when used with multiple channels in Go?

easy
A. It waits until one of the channels is ready to send or receive and executes that case.
B. It executes all channel operations simultaneously regardless of readiness.
C. It blocks forever until all channels are ready at the same time.
D. It randomly picks a channel to operate on without checking readiness.

Solution

  1. Step 1: Understand select behavior

    The select statement waits for one of its channel cases to be ready.
  2. Step 2: Identify how select chooses a case

    It picks one of the channels that is ready to send or receive and runs that case.
  3. Final Answer:

    It waits until one of the channels is ready to send or receive and executes that case. -> Option A
  4. Quick Check:

    Select waits for ready channel = A [OK]
Hint: Select picks the first ready channel to act on [OK]
Common Mistakes:
  • Thinking select runs all channels at once
  • Believing select waits for all channels simultaneously
  • Assuming select picks channels randomly without readiness check
2.

Which of the following is the correct syntax to use select with two channels ch1 and ch2 for receiving values?

?
easy
A. select { case val = <-ch1: fmt.Println(val) case val = <-ch2: fmt.Println(val) }
B. select { case <-ch1: fmt.Println(val) case <-ch2: fmt.Println(val) }
C. select { case val := ch1: fmt.Println(val) case val := ch2: fmt.Println(val) }
D. select { case val := <-ch1: fmt.Println(val) case val := <-ch2: fmt.Println(val) }

Solution

  1. Step 1: Check channel receive syntax

    Receiving from a channel uses val := <-ch to assign the received value.
  2. Step 2: Verify select case syntax

    Each case must have a receive operation with assignment like val := <-ch1.
  3. Final Answer:

    select { case val := <-ch1: fmt.Println(val) case val := <-ch2: fmt.Println(val) } -> Option D
  4. Quick Check:

    Correct receive syntax uses := <-channel [OK]
Hint: Use := <-channel to receive inside select case [OK]
Common Mistakes:
  • Using = instead of := for assignment
  • Omitting the <- operator for receiving
  • Trying to assign channel itself instead of received value
3.

What will be the output of the following Go program?

package main
import (
    "fmt"
    "time"
)
func main() {
    ch1 := make(chan string)
    ch2 := make(chan string)
    go func() {
        time.Sleep(100 * time.Millisecond)
        ch1 <- "hello"
    }()
    go func() {
        time.Sleep(50 * time.Millisecond)
        ch2 <- "world"
    }()
    select {
    case msg1 := <-ch1:
        fmt.Println(msg1)
    case msg2 := <-ch2:
        fmt.Println(msg2)
    }
}
medium
A. hello
B. world
C. hello world
D. No output (deadlock)

Solution

  1. Step 1: Analyze goroutine sleep durations

    The goroutine sending to ch2 sleeps 50ms, and ch1 sleeps 100ms.
  2. Step 2: Determine which channel is ready first

    Since ch2 sends first, the select will receive from ch2 and print "world".
  3. Final Answer:

    world -> Option B
  4. Quick Check:

    Channel with shorter sleep sends first = world [OK]
Hint: Select picks channel ready first (shorter sleep) [OK]
Common Mistakes:
  • Assuming ch1 sends first because it is listed first
  • Expecting both messages to print
  • Thinking select waits for all channels
4.

Identify the error in this Go code using select with multiple channels:

package main
import "fmt"
func main() {
    ch1 := make(chan int)
    ch2 := make(chan int)
    select {
    case val := <-ch1:
        fmt.Println(val)
    case val := <-ch2:
        fmt.Println(val)
    }
}
medium
A. Channels must be buffered to use select.
B. The select statement syntax is invalid without a loop.
C. The program will deadlock because channels are never written to.
D. The default case is not allowed in select statements.

Solution

  1. Step 1: Analyze channel creation

    Channels ch1 and ch2 are unbuffered with no goroutines to send values.
  2. Step 2: Select behavior without senders

    The select blocks forever since no channels become ready, causing a deadlock.
  3. Final Answer:

    The program will deadlock because channels are never written to. -> Option C
  4. Quick Check:

    No senders + no default = deadlock [OK]
Hint: No senders and no default causes deadlock [OK]
Common Mistakes:
  • Thinking channels must be buffered to use select
  • Believing select syntax is invalid without a loop
  • Assuming a default case is required or invalid
5.

You want to write a Go function that waits on two channels chA and chB and returns the first value received from either. If neither channel is ready immediately, it should return "timeout" after 100 milliseconds. Which select structure correctly implements this?

hard
A. select { case val := <-chA: return val case val := <-chB: return val case <-time.After(100 * time.Millisecond): return "timeout" }
B. select { case val := <-chA: return val case val := <-chB: return val default: time.Sleep(100 * time.Millisecond) return "timeout" }
C. select { case val := <-chA: return val case val := <-chB: return val case <-time.Tick(100 * time.Millisecond): return "timeout" }
D. select { case val := <-chA: return val case val := <-chB: return val case <-time.After(100): return "timeout" }

Solution

  1. Step 1: Use time.After for timeout

    The time.After function returns a channel that sends a value after the specified duration, perfect for timeout.
  2. Step 2: Check select cases

    Cases for receiving from chA and chB return the first received value; the timeout case returns "timeout" after 100ms.
  3. Step 3: Validate other options

    select { case val := <-chA: return val case val := <-chB: return val default: time.Sleep(100 * time.Millisecond) return "timeout" } uses default with sleep which blocks select; select { case val := <-chA: return val case val := <-chB: return val case <-time.Tick(100 * time.Millisecond): return "timeout" } uses time.Tick which repeats; select { case val := <-chA: return val case val := <-chB: return val case <-time.After(100): return "timeout" } uses incorrect duration type.
  4. Final Answer:

    select { case val := <-chA: return val case val := <-chB: return val case <-time.After(100 * time.Millisecond): return "timeout" } -> Option A
  5. Quick Check:

    Use time.After channel for timeout in select [OK]
Hint: Use time.After channel for timeout in select [OK]
Common Mistakes:
  • Using default with sleep instead of time.After
  • Using time.Tick which repeats instead of time.After
  • Passing wrong duration type to time.After
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard