From e9744427aa678754793a8ea9e9d1d9021a3d565a Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Fri, 21 Sep 2012 08:13:55 -0700 Subject: [PATCH] synchronization --- 039-synchronization.go | 31 ++++++++++++++++++------------- 040-select.go | 4 ++-- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/039-synchronization.go b/039-synchronization.go index 2d52a04..acbe6d8 100644 --- a/039-synchronization.go +++ b/039-synchronization.go @@ -1,18 +1,23 @@ -package main - -import "fmt" +package main // We can use channels to synchronize execution + // accross goroutings. Here's an example of waiting +import "fmt" // for another gorouting to finish. import "time" -func printer(done chan<- bool) { - for i := 0; i < 10; i++ { - time.Sleep(time.Millisecond * 100) - fmt.Println(i) - } - done <- true +func worker(done chan<- bool) { // The `done` channel will be used for + fmt.Print("Working...") // synchronization. + time.Sleep(time.Second) + fmt.Println(" done") + done <- true // Send a value to notify that the work is done. } func main() { - done := make(chan bool, 1) - go printer(done) - <- done -} + done := make(chan bool, 1) // Start a worker goroutine, give it the channel to + go worker(done) // notify on. + + <- done // Block until we can receive a value from the worker +} // over the channel. + +/* +$ go run synchronization.go // If you commented out the `<- done` line, the +Working... done // program would exit before the `worker` even +*/ // started. diff --git a/040-select.go b/040-select.go index fe78174..6698196 100644 --- a/040-select.go +++ b/040-select.go @@ -8,11 +8,11 @@ func main() { d := make(chan bool, 1) go func() { - time.Sleep(time.Millisecond * 1500) + time.Sleep(time.Second * 1) c1 <- "from 1" }() go func() { - time.Sleep(time.Millisecond * 2000) + time.Sleep(time.Second * 2) c2 <- "from 2" }()