synchronization

This commit is contained in:
Mark McGranaghan 2012-09-21 08:13:55 -07:00
parent 5d217ce5c1
commit e9744427aa
2 changed files with 20 additions and 15 deletions

View File

@ -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.

View File

@ -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"
}()