Menu Close

Go – How to pause the execution of goroutine in go

Here, We are going to learn about how to pause the execution of goroutine in go and what function will be used to pause the goroutine with program.

We use Sleep() function of time package to pause the execution of current goroutine in go.

Function prototype:

func Sleep(d Duration)

d: Time duration

Return type:

If we give negative or zero value for time duration, causes Sleep() function to return immediately. 

Example with code:

package main

import (

  "fmt"
  "time"

)

func main() {

  start_time := time.Now()

  time.Sleep(10 * time.Millisecond)

  end_time := time.Now()

  elapsed := end_time.Sub(start_time)

  fmt.Println("Elapsed time:  ", elapsed)
}

Output:

Elapsed time: 11.738761ms

Program:

package main

import (

  "fmt"
  "time"
  "sync"

)

func show_table(wg *sync.WaitGroup ){

  for i := 1; i <= 10; i++ {

    fmt.Println(i * 2)

    time.Sleep(1 * time.Millisecond)

  }

  wg.Done()

}
func main() {

  var wg sync.WaitGroup

  wg.Add(1)

  go show_table(&wg)

  wg.Wait()
}

Output:

2
4
6
8
10
12
14
16
18
20

To learn more about golang, You can refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

 https://golang.org/doc/
 https://golang.org/pkg/
Posted in golang, time

Leave a Reply

Your email address will not be published. Required fields are marked *