How to pause the execution of current Goroutine?


As a Go developer, you may need to pause the execution of a Goroutine at some point. Pausing the Goroutine can be helpful in scenarios such as waiting for input from the user, waiting for a response from a server, or to prevent a race condition.

In this article, we will explore various methods to pause the execution of the current Goroutine in Go.

Method 1: Using time.Sleep()

The simplest way to pause the execution of the Goroutine is by using the time.Sleep() function. This function takes a duration as an argument and pauses the execution of the Goroutine for the given duration.

Example

Here's an example −

package main

import (
   "fmt"
   "time"
)

func main() {
   fmt.Println("Start")
   time.Sleep(5 * time.Second)
   fmt.Println("End")
}

Output

Start
End

Method 2: Using sync.WaitGroup

Another way to pause the execution of the Goroutine is by using the sync.WaitGroup. This method is useful when you want to wait for a group of Goroutines to finish their execution before continuing.

Example

Here's an example −

package main

import (
   "sync"
)

func main() {
   var wg sync.WaitGroup
   wg.Add(1)

   go func() {
      defer wg.Done()
      // Do some work
   }()

   wg.Wait()
   // Continue after all Goroutines finish their execution
}

In the above example, the main Goroutine waits for the Goroutine inside the anonymous function to finish its execution using the wg.Wait() method.

Method 3: Using Channels

Channels can also be used to pause the execution of the Goroutine. You can send a value to the channel and wait for the Goroutine to receive it before continuing with the execution.

Example

Here's an example −

package main

import (
   "fmt"
)
   
func main() {
   c := make(chan bool)
   
   go func() {
      // Do some work
      c <- true
   }()
   
   <-c // Wait for the Goroutine to send the value
   // Continue after the Goroutine sends the value
   fmt.Println("Goroutine finished")
}

In the above example, the main Goroutine waits for the Goroutine inside the anonymous function to receive the value from the channel before continuing with the execution.

Output

Goroutine finished

Conclusion

Pausing the execution of the current Goroutine can be helpful in various scenarios. In this article, we explored three different methods to pause the execution of the Goroutine, including using time.Sleep(), sync.WaitGroup, and channels. Each method has its advantages and disadvantages, and you should choose the method that best suits your use case.

Updated on: 25-Apr-2023

799 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements