Golang 如何暂停当前Goroutine的执行
Goroutine是一个独立执行的函数或方法,与程序中存在的任何其他Goroutine同时执行。换句话说,Go语言中每个同时执行的活动都被称为Goroutine。所以在Go语言中,你可以使用 Sleep() 函数来暂停当前的Goroutine的执行。
这个函数使当前的Goroutine至少暂停指定的时间,在完成指定的时间后,Goroutine会自动唤醒并恢复其工作。如果该函数的值为负数或零,则该函数立即返回。它被定义在时间包中,所以你必须在你的程序中导入时间包以访问Sleep函数。
语法
func Sleep(d_value Duration)
这里, d_value 代表你想让当前goroutine休眠的时间长度。它可以是秒、毫秒、纳秒、微秒、分米等等。让我们借助给定的例子来讨论这个概念。
例1 :
// 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")
}
输出
Hello
GeeksforGeeks
GeeksforGeeks
Hello
Hello
GeeksforGeeks
GeeksforGeeks
例2 :
// 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")
}
输出
Bye
Bye
Bye
Bye
极客教程