Created
August 22, 2015 19:22
-
-
Save User4574/5058a984f3286f9e9467 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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