习惯了Go语言协程的用法,再来学习Python协程的时候,总感觉用起来哪里不太对,越用越不对劲。于是乎,就想研究一下它们到底有哪些区别!
在 Python 和 Go 中,协程的行为确实有一些关键的区别,主要体现在调度机制和代码的执行方式上。
调度机制 Python 的协程是非阻塞的,但需要显式调度,而 Go 的协程由运行时自动调度,不需要显式等待。
1.Go 协程(Goroutine) Go 的协程(goroutine)是轻量级的线程,由 Go 运行时自动调度。当启动一个 goroutine 时,它会立即开始运行,而主程序会继续执行后续代码,不会等待 goroutine 完成。
package main import (
"fmt"
"time"
) func myGoroutine() {
fmt.Println("Goroutine started")
time.Sleep(2 * time.Second)
fmt.Println("Goroutine finished")
} func main() {
go myGoroutine() // 启动 goroutine
fmt.Println("Main continues running")
time.Sleep(3 * time.Second) // 等待一段时间,确保 goroutine 完成
fmt.Println("Main finished")
}
运行结果:
Main continues running Goroutine started Goroutine finished Main finished
2.Python 协程 Python 的协程需要显式地通过 await(暂停当前协程的执行,等待另一个协程或 Future 完成) 来暂停和恢复执行。当启动一个协程时,它不会立即运行,而是需要被事件循环调度。如果你使用 await,当前协程会暂停,等待被调度的任务完成。
import asyncio async def my_coroutine():
print("Coroutine started")
await asyncio.sleep(2)
print("Coroutine finished")
async def main():
task = asyncio.create_task(my_coroutine()) # 启动协程
print("Task created, continuing execution")
await asyncio.sleep(1) # 主程序继续运行
print("Doing other work")
await task # 等待协程完成
print("Task completed")
asyncio.run(main())
运行结果:
Task created, continuing execution Doing other work Coroutine started Coroutine finished Task completed