Skip to content

Instantly share code, notes, and snippets.

@KentaKudo
Last active February 3, 2019 15:55
Show Gist options
  • Save KentaKudo/6d683f7a11194ce1a37e8fb801335165 to your computer and use it in GitHub Desktop.
Save KentaKudo/6d683f7a11194ce1a37e8fb801335165 to your computer and use it in GitHub Desktop.
A sample implementation of a task queue in go
// Inspired by Go in Action: Chapter 7 – Concurrency patterns
// https://www.manning.com/books/go-in-action
package main
import (
"fmt"
"os"
"sync"
)
// Task represents an interface of a workload.
type Task interface {
Process()
}
// Queue represents the task queue data structure.
type Queue struct {
ch chan Task
wg sync.WaitGroup
}
// New creates a new queue and starts workers with the specified number.
func New(numWorkers, queueCap int) *Queue {
q := &Queue{ch: make(chan Task, queueCap)}
q.wg.Add(numWorkers)
for i := 0; i < numWorkers; i++ {
go func() {
for t := range q.ch {
t.Process()
}
q.wg.Done()
}()
}
return q
}
// Run puts a task on the queue. It can be blocked according to the capacity of the queue.
func (q *Queue) Run(t Task) {
q.ch <- t
}
// Close closes the channel draining all the workload.
func (q *Queue) Close() {
close(q.ch)
q.wg.Wait()
}
func main() {
q := New(10, 3)
defer q.Close()
for _, t := range getTasks() { // Looping over a channel could be useful in some cases.
q.Run(t)
}
}
type task struct {
name string
}
func (t *task) Process() {
fmt.Fprintln(os.Stdout, t.name)
}
func getTasks() []Task {
return []Task{&task{"Kenta"}, &task{"Geroge"}, &task{"Tom"}, &task{"Daniel"}}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment