简体   繁体   English

goroutine和thread之间的区别

[英]the difference between goroutine and thread

I'm a newbie on Golang and I just learnt about the conception Goroutine with an example below: 我是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")
}

Here is one result of execution: 这是执行的一个结果:

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

done

I can see that goroutine and goroutine2 appeared alternately. 我可以看到goroutinegoroutine2交替出现。 So for me it looks like the multi-threading. 所以对我来说它看起来像多线程。
I've been told that Goroutine is lighter than thread. 我被告知Goroutine比线程轻。 So I just want to know what is exactly the difference between them, why doesn't Go use the routine instead of multi-thread? 所以我只是想知道它们之间究竟有什么区别,为什么Go不使用例程而不是多线程?

Thread is a natural OS object it's have enough. 线程是一个很自然的OS对象。 Threads manipulations are expensive operations. 线程操作是昂贵的操作。 They require switch to kernel return back, save and restore stack and so on. 它们需要切换回内核返回,保存和恢复堆栈等。 Many servers used threads but it's unreal to keep a lot of threads and do not go out of resources. 许多服务器使用线程但是保留大量线程并且不会耗尽资源是不真实的。 Also there's a special task to synchronize them. 还有一项特殊任务是同步它们。

So new concept emerged - coroutine or coprogram. 因此出现了新的概念 - 协程或coprogram。 They could be imagined as parts of execution path between synchronization points: input-output, send-receive so on. 它们可以被想象为同步点之间的执行路径的一部分:输入 - 输出,发送 - 接收等。 They are very light and could be better orchestrated 它们非常轻,可以更好地精心策划

So “threads but better”. 所以“线程更好”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM