dongshilve4392 2017-10-26 02:15
浏览 65
已采纳

goroutine和线程之间的区别

I'm a newbie on Golang and I just learnt about the conception Goroutine with an example below:

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. So for me it looks like the multi-threading.
I've been told that Goroutine is lighter than thread. So I just want to know what is exactly the difference between them, why doesn't Go use the routine instead of multi-thread?

  • 写回答

1条回答 默认 最新

  • douquan2023 2017-10-26 05:31
    关注

    Thread is a natural OS object it’s have enough. 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. 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”.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序