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 package main // We can use channels to synchronize execution
// accross goroutings. Here's an example of waiting
import "fmt" import "fmt" // for another gorouting to finish.
import "time" import "time"
func printer(done chan<- bool) { func worker(done chan<- bool) { // The `done` channel will be used for
for i := 0; i < 10; i++ { fmt.Print("Working...") // synchronization.
time.Sleep(time.Millisecond * 100) time.Sleep(time.Second)
fmt.Println(i) fmt.Println(" done")
} done <- true // Send a value to notify that the work is done.
done <- true
} }
func main() { func main() {
done := make(chan bool, 1) done := make(chan bool, 1) // Start a worker goroutine, give it the channel to
go printer(done) go worker(done) // notify on.
<- done
} <- 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) d := make(chan bool, 1)
go func() { go func() {
time.Sleep(time.Millisecond * 1500) time.Sleep(time.Second * 1)
c1 <- "from 1" c1 <- "from 1"
}() }()
go func() { go func() {
time.Sleep(time.Millisecond * 2000) time.Sleep(time.Second * 2)
c2 <- "from 2" c2 <- "from 2"
}() }()