Go 协程:并发编程的必备技能

277 阅读2分钟

什么是协程?

协程,也称为轻量级线程,是一种用户态的并发执行单元。与操作系统线程相比,协程更加轻量级,创建和销毁的开销更小,切换速度更快。Go 语言的协程被称为 goroutine,它由 Go 运行时管理,而不是操作系统。

如何使用协程?

在 Go 语言中,使用 go 关键字是创建协程最基本的方法。当我们在函数调用前添加 go 关键字时,Go 运行时会将该函数作为一个协程启动。

package main

import (
	"fmt"
	"time"
)

func task(id int) {
	fmt.Printf("Task %d started\n", id)
	time.Sleep(time.Second) // 模拟耗时操作
	fmt.Printf("Task %d finished\n", id)
}

func main() {
	for i := 1; i <= 5; i++ {
		go task(i) // 启动一个 goroutine 执行 task 函数
	}

	time.Sleep(time.Second * 2) // 等待所有 goroutine 执行完成
	fmt.Println("Main function finished")
}

代码解释:

  • go task(i):使用 go 关键字启动一个 goroutine 执行 task 函数,每个 goroutine 都会打印开始和结束信息,并模拟一个耗时操作。
  • time.Sleep(time.Second * 2):主 goroutine 等待 2 秒,确保所有子 goroutine 有足够的时间执行完成。

运行结果:

Task 2 started
Task 3 started
Task 5 started
Task 4 started
Task 1 started
Task 1 finished
Task 3 finished
Task 5 finished
Task 2 finished
Task 4 finished
Main function finished

可以看到,多个 task 函数并发执行,而不是顺序执行,并且每次运行顺序不确定。

协程与 Channel 的配合

协程通常与 channel 配合使用,实现 goroutine 之间的通信和同步。Channel 是一种类型安全的管道,用于在 goroutine 之间传递数据。

package main

import (
	"fmt"
	"time"
)

func producer(ch chan int) {
	for i := 1; i <= 5; i++ {
		ch <- i // 将数据发送到 channel
		fmt.Printf("Producer sent: %d\n", i)
		time.Sleep(time.Millisecond * 500)
	}
	close(ch) // 关闭 channel
}

func consumer(ch chan int) {
	for data := range ch { // 从 channel 接收数据
		fmt.Printf("Consumer received: %d\n", data)
		time.Sleep(time.Millisecond * 200)
	}
}

func main() {
	ch := make(chan int) // 创建一个 channel
	go producer(ch)      // 启动 producer goroutine
	go consumer(ch)      // 启动 consumer goroutine

	time.Sleep(time.Second * 5)
	fmt.Println("Main function finished")
}

代码解释:

  • make(chan int):创建一个用于传递整数的 channel。
  • producer 函数:向 channel 发送数据。
  • consumer 函数:从 channel 接收数据。
  • close(ch):关闭 channel,表示不再发送数据。
  • for data := range ch:从 channel 接收数据,直到 channel 关闭。

运行结果:

Producer sent: 1
Consumer received: 1
Producer sent: 2
Consumer received: 2
Producer sent: 3
Consumer received: 3
Producer sent: 4
Consumer received: 4
Producer sent: 5
Consumer received: 5
Main function finished

可以看到,producer 和 consumer 两个 goroutine 通过 channel 实现了数据的传递和同步。

总结

Go 语言的协程(goroutine)是一种轻量级、高效的并发机制,它使得并发编程变得更加简单和高效。通过与 channel 的配合使用,可以轻松地构建高性能、可扩展的应用程序。

感谢阅读!如果你觉得这篇文章对你有帮助,请分享给你的朋友们,让更多的人一起学习Go语言!