How to pause the execution of current Goroutine?

A Goroutine is a function or method which executes independently and simultaneously in connection with any other Goroutines present in your program. Or in other words, every concurrently executing activity in Go language is known as a Goroutines. So in Go language, you are allowed to pause the execution of the current goroutine by using Sleep() function.
This function pauses the current goroutine for at least the specified duration, after completing the specified duration the goroutine wakes up automatically and resume its working. If the value of this function is negative or zero then this function return immediately. It is defined under the time package so, you have to import time package in your program for accessing Sleep function.

Syntax:

func Sleep(d_value Duration)

Here, d_value represents the time duration in which you want to sleep the current goroutine. It may be in Seconds, Milliseconds, Nanoseconds, Microseconds, Minutesm, etc. Let us discuss this concept with the help of the given examples:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program to illustrate how
// to put a goroutine to sleep
package main
  
import (
    "fmt"
    "time"
)
  
func show(str string) {
  
    for x := 0; x < 4; x++ {
        time.Sleep(300 * time.Millisecond)
        fmt.Println(str)
    }
}
  
// Main Function
func main() {
  
    // Calling Goroutine
    go show("Hello")
  
    // Calling function
    show("GeeksforGeeks")
}

chevron_right


Output:

Hello
GeeksforGeeks
GeeksforGeeks
Hello
Hello
GeeksforGeeks
GeeksforGeeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program to illustrate how
// to put a goroutine to sleep
package main
  
import (
    "fmt"
    "time"
)
  
// Here, the value of Sleep function is zero
// So, this function return immediately.
func show(str string) {
  
    for x := 0; x < 4; x++ {
      
        time.Sleep(0 * time.Millisecond)
        fmt.Println(str)
    }
}
  
// Main Function
func main() {
  
    // Calling Goroutine
    go show("Hello")
  
    // Calling function
    show("Bye")
}

chevron_right


Output:

Bye
Bye
Bye
Bye


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.