习惯了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

阅读剩余 0%
本站所有文章资讯、展示的图片素材等内容均为注册用户上传(部分报媒/平媒内容转载自网络合作媒体),仅供学习参考。 用户通过本站上传、发布的任何内容的知识产权归属用户或原始著作权人所有。如有侵犯您的版权,请联系我们反馈本站将在三个工作日内改正。