Python与Go协程的差异与共通之处
学习了Python协程后,你可能会对Go语言的协程产生疑问。其实,两者在协程的核心概念上是一致的:非阻塞、非独占,并在同一CPU核心上共享时间片。
然而,具体的实现方式却有所不同:
Go语言协程
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 3; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("hello world")
time.Sleep(1 * time.Second)
fmt.Println("over!")
}
Python协程
import asyncio
async def say(s):
for _ in range(3):
await asyncio.sleep(0.1)
print(s)
async def over():
await asyncio.sleep(1)
print('over!')
async def main():
await asyncio.gather(
say('hello world'),
over()
)
asyncio.run(main())
关键区别:
asyncio
库。goroutine
,Python使用asyncio
协程。总而言之,Go和Python协程都是实现并发编程的有效手段,其差异主要体现在语法和集成方式上,而非核心概念。 理解协程的底层机制和应用场景才是关键。