习惯了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
在 Python 中,asyncio.create_task(my_coroutine()) 启动协程后,主程序会继续执行,不会等待协程完成。只有在使用 await task 时,主程序才会暂停,等待协程完成。
加深理解
事件循环可以把它理解成 一个无限循环的死循环:
- 一个进程,可以有多个线程 ✅(这是操作系统常识)
- 一个线程,只能有一个事件循环 ✅(协程框架铁律)
所以:一个进程,可以拥有 N 个事件循环(每个线程一个)
Swoole 的 Co\run() = Python asyncio 的 asyncio.run(),它们的作用完全一样:启动事件循环 + 协程入口
Go runtime = 自带协程容器 + 事件循环,main 函数 = 自动跑在里面
文章标题:Golang协程和Python协程用法上的那些“不一样”
文章链接:https://www.muooy.cn/7765.html
更新时间:2026年04月11日
1.本站大部分内容均收集于网络!若内容若侵犯到您的权益,请发送邮件至:305582964@qq.com,我们将第一时间处理!2.资源所需价格并非资源售卖价格,是收集、整理、编辑详情以及本站运营的适当补贴,并且本站不提供任何免费技术支持。
3.所有资源仅限于参考和学习,版权归原作者所有,更多请阅读用户协议和免责声明。


Go的goroutine自动调度,Python协程需显式调度,两种方式各有千秋,对并发处理有不同考量呀!🤔