goroutine和thread的区别
the difference between goroutine and thread
我是 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
我看到goroutine
和goroutine2
交替出现了。所以对我来说它看起来像多线程。
有人告诉我 Goroutine 比线程更轻。所以我只想知道它们到底有什么区别,为什么Go不使用例程而是多线程?
Thread 是一个天然的 OS 对象,它已经足够了。线程操作是昂贵的操作。他们需要切换到内核 return 回来,保存和恢复堆栈等等。许多服务器使用线程,但保留大量线程并且不耗尽资源是不现实的。还有一个特殊的任务来同步它们。
于是出现了新的概念——协程或协同程序。它们可以被想象成同步点之间执行路径的一部分:输入-输出、发送-接收等等。它们很轻,可以更好地编排
所以“线程但更好”。
我是 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
我看到goroutine
和goroutine2
交替出现了。所以对我来说它看起来像多线程。
有人告诉我 Goroutine 比线程更轻。所以我只想知道它们到底有什么区别,为什么Go不使用例程而是多线程?
Thread 是一个天然的 OS 对象,它已经足够了。线程操作是昂贵的操作。他们需要切换到内核 return 回来,保存和恢复堆栈等等。许多服务器使用线程,但保留大量线程并且不耗尽资源是不现实的。还有一个特殊的任务来同步它们。
于是出现了新的概念——协程或协同程序。它们可以被想象成同步点之间执行路径的一部分:输入-输出、发送-接收等等。它们很轻,可以更好地编排
所以“线程但更好”。