Channel synchronization in Golang

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 

In the above code, we synchronized the code as the

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 

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!
Updated on: 2021-11-01T06:51:24+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements