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) }
More Related questions...