Created
October 1, 2014 08:58
-
-
Save ilovejs/937c70a9e985be72e6b9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"time" | |
) | |
//http://www.goinggo.net/2014/02/the-nature-of-channels-in-go.html | |
func main() { | |
// Create an unbuffered channel | |
baton := make(chan int) | |
// First runner to his mark | |
go Runner(baton) | |
// Start the race | |
baton <- 1 | |
// Give the runners time to race | |
time.Sleep(500 * time.Millisecond) | |
} | |
func Runner(baton chan int) { | |
var newRunner int | |
// Wait to receive the baton | |
runner := <-baton | |
// Start running around the track | |
fmt.Printf("Runner %d Running With Baton\n", runner) | |
// New runner to the line | |
if runner != 4 { | |
newRunner = runner + 1 | |
fmt.Printf("Runner %d To The Line\n", newRunner) | |
//call itself | |
go Runner(baton) | |
} | |
// Running around the track | |
time.Sleep(100 * time.Millisecond) | |
// Is the race over | |
if runner == 4 { | |
fmt.Printf("Runner %d Finished, Race Over\n", runner) | |
return | |
} | |
// Exchange the baton for the next runner | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment