Golang / GoLang Concurrency Mastery Interview Questions
How does Go's select handle multiple ready cases, and how do you implement true priority?
When multiple cases in a select are simultaneously ready, Go picks one uniformly at random. This prevents deterministic starvation but does not guarantee priority. Implementing true priority requires nested selects or a dedicated check before the main select.
// Standard select: random among ready cases // Even if ctx is cancelled AND a job is ready, ~50% of the time the job wins for { select { case <-ctx.Done(): return case job := <-jobs: process(job) } } // Priority select: always check cancellation first // Step 1: fast non-blocking check of the high-priority case for { select { case <-ctx.Done(): return // check first: if done, exit immediately default: // not done: fall through to main select } // Step 2: main blocking select select { case <-ctx.Done(): return case job := <-jobs: process(job) } } // True channel priority (hi > lo): nested select pattern func drainWithPriority(hi, lo <-chan int) { for { // Always drain hi before touching lo select { case v := <-hi: handle(v); continue default: } // hi empty: process either select { case v := <-hi: handle(v) case v := <-lo: handle(v) } } }
More Related questions...