Channel synchronization in Golang

Go ProgrammingServer Side ProgrammingProgramming

We can make use of channels if we want to synchronize goroutines. By synchronizing, we want to make the goroutines work in a defined manner, for example, not starting the next goroutine until the previous one has finished its execution.

The channels help in achieving that, as they can be used to block the process and then can also be used to notify the second goroutine that the previous goroutine has finished its job.

Example 1

Let's consider a very basic example of channel synchronization where we will see how we can achieve it with the help of a buffered channel.

Consider the code shown below.

package main

import (
   "fmt"
   "time"
)

func check(done chan bool) {
   fmt.Print("Welcome to...")
   time.Sleep(time.Second)
   fmt.Println("TutorialsPoint")

   done <- true
}

func main() {
   done := make(chan bool, 1)
   go check(done)

   <-done
}

In the above code, we synchronized the code as the <- done is simply blocking the code and unless and until it receives the value, which we are doing inside the check function, it won't let anything else execute.

If we use the command go run main.go on the above code, we will see the following output.

Output

Welcome to...TutorialsPoint

Example 2

The above example can be used to enhance the synchronization further as with it, we can make one goroutine wait for another goroutine.

Consider the code shown below.

package main

import (
   "fmt"
   "time"
)

func check(done chan bool) {
   fmt.Print("Welcome to...")
   time.Sleep(time.Second)
   fmt.Println("TutorialsPoint")

   done <- true
}

func check2() {
   fmt.Println("Learn Go from here!")
}

func main() {
   done := make(chan bool, 1)
   go check(done)

   if <-done {
      go check2()
      time.Sleep(time.Second)
   }
}

Output

If we use the command go run main.go on the above code, we will see the following output.

Welcome to...TutorialsPoint
Learn Go from here!
raja
Published on 01-Nov-2021 06:51:24
Advertisements