Go Concurrency Interview: Alternating Print with Dual‑Channel Relay Technique

This article dissects the classic Go interview problem of printing numbers and letters alternately (1a2b…26z), explains why sleep‑based solutions fail, details deadlock and token‑count pitfalls, and presents a robust dual‑channel token relay implementation with step‑by‑step code and three key takeaways.

Tinker Programmer
Tinker Programmer
Tinker Programmer
Go Concurrency Interview: Alternating Print with Dual‑Channel Relay Technique

The task is to launch two goroutines that print numbers 1‑26 and letters a‑z in strict alternation, producing the sequence 1a2b3c...26z. The author first shows a naive attempt that relies on time.Sleep to guess ordering, which yields garbled output because sleep durations are magic numbers, do not guarantee precise alternation, and merely hide the coordination problem.

Pitfall 1: Using sleep to force order – three reasons are given: the sleep duration is arbitrary, it cannot ensure exact alternation across machines, and it avoids solving the real synchronization issue. Interviewers view this approach negatively.

Pitfall 2: Both goroutines waiting to receive first (deadlock) – if each goroutine executes <-ch before sending, they block forever. The solution is for the main goroutine to send the initial token, breaking the deadlock.

Pitfall 3: Mismatched token counts – the number goroutine sends a token after each print, but the last iteration should not send because the letter goroutine finishes, leading to either a missing final character or a leaked goroutine waiting on a never‑sent token.

Pitfall 4: Main goroutine exiting early – returning from main before child goroutines finish kills them. Using a sync.WaitGroup to wait for both workers solves this.

The correct implementation uses two channels as tokens: numCh (number token) and alphaCh (letter token). The main goroutine sends the first token on numCh. The number goroutine receives from numCh, prints a number, then sends a token on alphaCh. The letter goroutine receives from alphaCh, prints a letter, and, unless it is the last iteration, sends a token back on numCh. A sync.WaitGroup ensures the program waits for both goroutines before exiting.

package main

import (
    "fmt"
    "sync"
)

func main() {
    numCh := make(chan struct{})   // token for number goroutine
    alphaCh := make(chan struct{}) // token for letter goroutine
    var wg sync.WaitGroup
    wg.Add(2)

    // number goroutine
    go func() {
        defer wg.Done()
        for i := 1; i <= 26; i++ {
            <-numCh               // wait for token
            fmt.Print(i)
            alphaCh <- struct{}{} // hand token to letter goroutine
        }
    }()

    // letter goroutine
    go func() {
        defer wg.Done()
        for i := 0; i < 26; i++ {
            <-alphaCh               // wait for token
            fmt.Printf("%c", rune('a'+i))
            if i < 25 { // last iteration does not send back a token
                numCh <- struct{}{}
            }
        }
    }()

    // start the relay
    numCh <- struct{}{}
    wg.Wait()
    fmt.Println()
}

Running the program prints the expected alternating sequence.

Three core takeaways:

Use channels as tokens; never rely on sleep for ordering.

Ensure one side sends the first token (typically the main goroutine) to avoid deadlock.

Match token sends to the actual number of required prints; omit the final token to prevent a blocked receiver.

These principles cover about 90% of alternation‑printing interview questions, preventing common failures due to sleep, deadlock, and goroutine leaks.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

deadlocksynchronizationgoroutineChannels
Tinker Programmer
Written by

Tinker Programmer

Solving problems with code, sharing practical tech insights, and leveling up together!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.