Synchronization Between Two Goroutines Using Channels in Golang and Waitgroup
In this blog we will synchronise two goroutines using channels and waitgroups#
package main
import "sync"
import "fmt"
var wg sync.WaitGroup
func even(evenCh, oddCh chan bool) {
for i := 1; i <= 10; i++ {
if i%2 == 0 {
<-evenCh
fmt.Println(i)
if i < 10 {
oddCh <- true
}
}
}
// close(oddCh)
wg.Done()
}
func odd(evenCh, oddCh chan bool) {
for i := 1; i <= 10; i++ {
if i%2 != 0 {
<-oddCh
fmt.Println(i)
if i < 10 {
evenCh <- true
}
}
}
// close(evenCh)
wg.Done()
}
func main() {
evenCh := make(chan bool)
oddCh := make(chan bool)
wg.Add(2)
go even(evenCh, oddCh)
go odd(evenCh, oddCh)
oddCh <- true
wg.Wait()
}
as we know goroutine is the biggest selling point of golang. if you do not know about goroutines don’t worry i will write a seperate blog for discussing goroutines in deep.
For now just know that groutines runs parallely and they are lightweight thread which is handled by go runtime.
we have used WaitGroup from sync
package. WaitGroup is very handy when it comes to deal with goroutines, it is basically adds lock on main thread with counter to global variable and wait for that counter till zero.
whenever we calls wg.Done()
it decrease the counter and when it is zero then it releases lock on main thread.
suppose you have two gorutines then you will add wg.Add(2)
and so on.
as you can see we have created unbuffered channels each for each function. unbuffered channels are blocking it will block the execution of code until recieves value in that channel.
even function sending signal to odd channel and odd function sending signal to even channel by this manner they both are running one by one only.
Output of the programme will look like below one it will be in sequence.
Output->
1
2
3
4
5
6
7
8
9
0