Skip to content

Instantly share code, notes, and snippets.

@niels-s
Last active December 1, 2016 10:28
Show Gist options
  • Save niels-s/11f63ab1a778b2f181baca0127e22ad0 to your computer and use it in GitHub Desktop.
Save niels-s/11f63ab1a778b2f181baca0127e22ad0 to your computer and use it in GitHub Desktop.
Example of partitioning message over internal channels in golang
package main
import (
"fmt"
"hash/fnv"
"strconv"
"sync"
"time"
)
func main() {
wg := sync.WaitGroup{}
numberOfWorkers := uint64(4)
channels := make([]chan string, numberOfWorkers)
for i := uint64(0); i < numberOfWorkers; i++ {
channels[int(i)] = make(chan string)
}
for i, c := range channels {
go process_queue(wg, i, c)
}
uids := []string{"niels", "jurriaan", "arno", "daan", "martijn", "cheffrey", "koen", "martijn", "cheffrey", "koen"}
h := fnv.New64a()
for _, uid := range uids {
h.Write([]byte(uid))
channels[h.Sum64()%numberOfWorkers] <- uid
h.Reset()
}
time.Sleep(time.Second * 1)
for _, c := range channels {
close(c)
}
wg.Wait()
}
func process_queue(wg sync.WaitGroup, n int, c chan string) {
name := strconv.Itoa(n)
for msg := range c {
fmt.Printf("Queue %s received: %s \n", name, msg)
}
wg.Done()
}
@arnov
Copy link

arnov commented Dec 1, 2016

Volgens mij spel je het als 'cheffrey'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment