Golang如何使用多个Goroutines?用法实例

2021年4月3日17:33:29 发表评论 735 次浏览

先决条件:多个Goroutines

Goroutine是一种函数或方法, 可与程序中存在的任何其他Goroutine一起独立且同时执行。换句话说, 每个Go语言中同时执行的活动称为Goroutines。在Go语言中, 允许你在一个程序中创建多个goroutine。你可以简单地通过使用go关键字作为函数或方法调用的前缀来创建goroutine, 如以下语法所示:

func name(){

// statements
}

// using go keyword as the 
// prefix of your function call
go name()

现在, 借助示例讨论如何创建和使用多个goroutine:

// Go program to illustrate Multiple Goroutines
package main
  
import (
     "fmt"
     "time"
)
  
// For goroutine 1
func Aname() {
  
     arr1 := [4]string{ "Rohit" , "Suman" , "Aman" , "Ria" }
  
     for t1 := 0; t1 <= 3; t1++ {
      
         time .Sleep(150 * time .Millisecond)
         fmt.Printf( "%s\n" , arr1[t1])
     }
}
  
// For goroutine 2
func Aid() {
  
     arr2 := [4] int {300, 301, 302, 303}
      
     for t2 := 0; t2 <= 3; t2++ {
      
         time .Sleep(500 * time .Millisecond)
         fmt.Printf( "%d\n" , arr2[t2])
     }
}
  
// Main function
func main() {
  
     fmt.Println( "!...Main Go-routine Start...!" )
  
     // calling Goroutine 1
     go Aname()
  
     // calling Goroutine 2
     go Aid()
  
     time .Sleep(3500 * time .Millisecond)
     fmt.Println( "\n!...Main Go-routine End...!" )
}

输出如下:

!...Main Go-routine Start...!
Rohit
Suman
Aman
300
Ria
301
302
303

!...Main Go-routine End...!

创建:在上面的示例中, 除了主goroutine, 我们还有两个goroutine, 即一个名字和援助。这里, 一个名字打印作者的姓名, 然后援助打印作者的ID。

加工:在这里, 我们有两个goroutine, 即一个名字和援助和一个主要的goroutine。当我们首先运行该程序时, 主要的goroutine策略会显示"!...主例程开始...!", 这里主要goroutine就像是一个父goroutine, 而其他goroutine是它的子代, 因此在其他goroutine启动之后首先运行main goroutine, 如果main goroutine终止, 那么其他goroutine也将终止。因此, 在主要goroutine之后, 一个名字和援助goroutines同时开始工作。的一个名字goroutine从开始工作150毫秒和援助从开始工作500毫秒如下图所示:

多个Goroutines1

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: