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)
}
}
}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
