Created
August 7, 2019 05:17
-
-
Save ilhamarrouf/4d1db971ade5b83d769251dfd1772c76 to your computer and use it in GitHub Desktop.
We can use channels to synchronize execution across goroutines. Here’s an example of using a blocking receive to wait for a goroutine to finish. When waiting for multiple goroutines to finish, you may prefer to use a WaitGroup.
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" | |
import "time" | |
func worker(done chan bool) { | |
fmt.Print("working...") | |
time.Sleep(time.Second) | |
fmt.Println("done") | |
// Send a value to notify that we're done. | |
done <- true | |
} | |
func main() { | |
// Start a worker goroutine, giving it the channel to | |
// notify on. | |
done := make(chan bool, 1) | |
go worker(done) | |
// Block until we receive a notification from the | |
// worker on the channel. | |
<-done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment