Golang / GoLang Concurrency Mastery Interview Questions
How do you use a buffered channel as a task queue with natural backpressure?
A buffered channel provides natural backpressure: the producer blocks when the queue is full, signalling the consumer cannot keep up. This prevents unbounded memory growth without any additional data structure and is idiomatic Go.
type TaskQueue struct {
tasks chan func()
quit chan struct{}
}
func NewTaskQueue(bufSize, workers int) *TaskQueue {
q := &TaskQueue{
tasks: make(chan func(), bufSize), // bounded queue
quit: make(chan struct{}),
}
for w := 0; w < workers; w++ { go q.worker() }
return q
}
func (q *TaskQueue) worker() {
for {
select {
case <-q.quit: return
case task := <-q.tasks: task()
}
}
}
// Submit blocks when queue is full — natural backpressure
func (q *TaskQueue) Submit(ctx context.Context, task func()) error {
select {
case q.tasks <- task:
return nil
case <-ctx.Done():
return ctx.Err() // caller's deadline expired waiting for a slot
}
}
// TrySubmit — non-blocking: drop if queue is full
func (q *TaskQueue) TrySubmit(task func()) bool {
select {
case q.tasks <- task: return true
default: return false
}
}
func (q *TaskQueue) Shutdown() { close(q.quit) }
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...
