Skip to content

Instantly share code, notes, and snippets.

@thenrich
Last active February 3, 2017 14:54
Show Gist options
  • Save thenrich/edaa085a625af66e01307b9a077fcf07 to your computer and use it in GitHub Desktop.
Save thenrich/edaa085a625af66e01307b9a077fcf07 to your computer and use it in GitHub Desktop.
Go queue
package main
import (
"fmt"
"time"
)
// Container for messages in the queue
type Message struct {
Msg string
}
// Launches workers
func workers(queue chan *Message) {
// Set the number of workers to create
numWorkers := 10
for x := 0; x < numWorkers; x++ {
// Work function, send the loop iteration so we know which
// worker is doing the work
go func(x int) {
for {
// Listen for a message on the queue
select {
case pop := <-queue:
fmt.Println("Got message from queue as worker: ", x)
fmt.Println("Message on queue: ", pop.Msg)
}
}
}(x)
}
}
func main() {
// Create queue with a buffer of 1
queue := make(chan *Message, 1)
// Start a 60s ticker
t := time.NewTicker(time.Second * 60)
// Start the workers
workers(queue)
// When ticker ticks, add several messages to the queue
for {
select {
case <-t.C:
go func() {
queue <- &Message{Msg: "Message"}
queue <- &Message{Msg: "Message"}
queue <- &Message{Msg: "Message"}
queue <- &Message{Msg: "Message"}
queue <- &Message{Msg: "Message"}
queue <- &Message{Msg: "Message"}
queue <- &Message{Msg: "Message"}
queue <- &Message{Msg: "Message"}
queue <- &Message{Msg: "Message"}
}()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment