Golang has support for concurrency using goroutines and channels.
In this article, we will talk about how to synchronize multiple goroutines with sync.WaitGroup
and channel
sync.WaitGroup
Used to wait for goroutines to finish executing
Add(delta int) // how many goroutines that you want to wait
Done() // call when goroutine finished, this method will reduce the number of goroutines waiting
Wait() // wait for all goroutines finisied then do next function
Channel
Channel is a pipeline for sending and receiving data between differenct goroutines
channel := make(chan <type>) // declare channel variable
chanel <- s_value // send value into a channel
r_value := <-chanel // receive a value from the channel
Let's Code!
func main(){
var wg sync.WaitGroup
var shared int
channel := make(chan bool)
wg.Add(3)
go func() {
defer wg.Done()
shared = rand.Intn(100)
close(channel)
fmt.Printf("Task1 Done | SET shared = %d ... \n",shared)
}()
go func () {
defer wg.Done()
//wait for Task1
<-channel
fmt.Printf("Task2 Done | GET shared = %d ... \n",shared)
}()
go func () {
defer wg.Done()
//wait for Task1
<-channel
fmt.Printf("Task3 Done | GET shared = %d ... \n",shared)
}()
wg.Wait()
fmt.Println("All done!")
}
Result
> go run main.go
Task1 Done | SET shared = 81 ...
Task2 Done | GET shared = 81 ...
Task3 Done | GET shared = 81 ...
All done!
How this code work?
this code is the program that contains 3 goroutines, the first goroutine is executed first to set the value to share variables and the last 2 goroutines are wait for the shared variable to be set then print the shared variable.
Top comments (0)