gpt4 book ai didi

multithreading - goroutine和thread的区别

转载 作者:IT王子 更新时间:2023-10-29 01:57:33 24 4
gpt4 key购买 nike

<分区>

我是 Golang 的新手,我刚刚通过以下示例了解了 Goroutine 的概念:

package main

import "fmt"

func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}

func main() {
f("direct")
go f("goroutine")
go f("goroutine2")
go func(msg string) {
fmt.Println(msg)
}("going")
var input string
fmt.Scanln(&input)
fmt.Println("done")
}

这是一个执行结果:

direct : 0
direct : 1
direct : 2
goroutine : 0
goroutine2 : 0
goroutine2 : 1
goroutine2 : 2
goroutine : 1
goroutine : 2
going

done

我可以看到 goroutinegoroutine2 交替出现。所以对我来说它看起来像多线程。
有人告诉我 Goroutine 比线程更轻。所以我只想知道它们之间到底有什么区别,为什么Go不使用例程而不是多线程?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com