Skip to content

Instantly share code, notes, and snippets.

@User4574
Created Aug 22, 2015
Embed
What would you like to do?
package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func main() {
start := time.Now()
ring(5, 100000)
elapsed := time.Since(start)
fmt.Printf("Time taken: %v\n", elapsed)
}
func ring(N int, M int) {
wg.Add(N)
chanarr := make([](chan int), N)
for i, _ := range chanarr {
chanarr[i] = make(chan int)
}
for i := 0; i < (N - 1); i++ {
go node(chanarr[i], chanarr[i+1])
}
go decnode(chanarr[N-1], chanarr[0])
chanarr[0] <- M
wg.Wait()
}
func node(this chan int, next chan int) {
for {
msg := <-this
next <- msg
if msg == 0 {
close(next)
wg.Done()
break
}
}
}
func decnode(this chan int, next chan int) {
for {
msg := <-this
if msg == 0 {
close(next)
wg.Done()
break
}
next <- (msg - 1)
}
}
// $ go build
// $ ./ring
// Time taken: 131.612955ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment