Goroutines

在 Go 语言中,我们使用 goroutines 来创建并发程序。并发程序能够同时运行多个进程。

假设我们有一个程序包含两个独立的函数。在普通程序中,这两个函数会同步执行。也就是说,第二个函数只有在第一个函数执行完毕后才会执行。

然而,由于这两个函数是独立的,如果我们能异步地同时执行这两个函数,那将是更高效的。

为此,我们使用 goroutines 来帮助我们在编程中实现并发。


创建 Goroutine

我们可以通过在调用函数时使用 go 关键字,将一个普通函数转换为一个 goroutine。例如:

func display() {
  // code inside the function
}

// start goroutine
go display()

这里,display() 就是一个 goroutine。


示例:Goroutine

现在让我们来看一个使用 goroutine 进行并发编程的实际示例。

package main
import (
  "fmt"
  "time"
)

// create a function
func display(message string) {

  fmt.Println(message)
}

func main() {

// call goroutine go display("Process 1")
display("Process 2") }

输出

Process 2

在上面的示例中,我们调用了 display() 函数两次

  • go display("Process 1") - 作为 goroutine
  • display("Process 2") - 普通函数调用

在正常执行过程中,程序控制在第一次函数调用时会转移到该函数,并在执行完成后返回到下一条语句。

在我们的示例中,下一条语句是第二次函数调用。所以,首先应该打印 Process 1,然后是 Process 2

然而,我们只得到了 Process 2 作为输出。

这是因为我们在第一次函数调用时使用了 go 关键字,所以它被视为一个 goroutine。该函数独立运行,而 main() 函数现在并发运行。

因此,第二次调用会立即执行,程序会在第一个函数调用完成之前终止。

In a program that uses Goroutine, the execution of processes is concurrent.
Goroutine 的工作原理

使用 Goroutine 同时运行两个函数

在并发程序中,main() 始终是一个默认的 goroutine。如果 main() 没有执行,其他 goroutine 也无法执行。

所以,为了确保所有 goroutines 在主函数结束前都能执行完毕,我们会让进程休眠,以便其他进程有机会执行。

// Program to run two goroutines concurrently

package main
import (
  "fmt"
  "time"
)

// create a function
func display(message string) {

  // infinite for loop
  for {
    fmt.Println(message)

    // to sleep the process for 1 second
    time.Sleep(time.Second * 1)
  }
}

func main() {

// call function with goroutine go display("Process 1")
display("Process 2") }

输出

Process 2
Process 1
...

在上面的示例中,我们在函数定义中添加了一行。

time.Sleep(time.Second * 1)

这里,当 display("Process 2") 执行时,time.Sleep() 函数会暂停进程 1 秒。在这 1 秒内,goroutine go display("Process 1") 会被执行。

这样,在 main() 函数停止之前,这些函数会并发运行。


多个 Goroutines

当同时运行多个 Goroutines 时,它们会并发地相互交互。 goroutine 的执行顺序是随机的,所以我们可能无法获得预期的输出。例如:

// Program to illustrate multiple goroutines

package main

import (
  "fmt"
  "time"
)

func display(message string) {

  fmt.Println(message)

}

func main() {

  // run two different goroutine
  go display("Process 1")
  go display("Process 2")
  go display("Process 3")

  // to sleep main goroutine for 1 sec
  time.Sleep(time.Second * 1)
}

输出

Process 3
Process 1
Process 2

这里,所有的 goroutines 都以 1 秒的睡眠时间并发运行。执行顺序是随机的,所以每次运行程序时,我们都会得到不同的输出。


Goroutines 的优点

以下是 goroutines 的一些主要优点。

  • 通过 Goroutines,在 Go 编程中实现了并发。它有助于两个或多个独立函数一起运行。
  • Goroutines 可用于在程序中运行后台操作。
  • 它通过私有通道进行通信,因此它们之间的通信更安全。
  • 使用 goroutines,我们可以将一个任务分成不同的部分以获得更好的性能。
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战