doumen5491 2018-10-24 17:56
浏览 95
已采纳

执行goroutine时的并发与并行

A fairly naive go question. I was going through go-concurrency tutorial and I came across this https://tour.golang.org/concurrency/4.

I modified the code to add a print statement in the fibonacci function. So the code looks something like

package main

import (
    "fmt"
)

func fibonacci(n int, c chan int) {
    x, y := 0, 1
    for i := 0; i < n; i++ {
        c <- x
        x, y = y, x+y
        fmt.Println("here")
    }
    close(c)
}

func main() {
    c := make(chan int, 10)
    go fibonacci(cap(c), c)
    for i := range c {
        fmt.Println(i)
    }
}

And I got this as an output

here
here
here
here
here
here
here
here
here
here
0
1
1
2
3
5
8
13
21
34

I was expecting here and the numbers to be interleaved. (Since the routine gets executed concurrently) I think I am missing something basic about go-routines. Not quite sure what though.

  • 写回答

2条回答 默认 最新

  • duandi4238 2018-10-24 22:43
    关注

    I think what you are observing is that Go has its own scheduler, and at the same time there is a distinction between "concurrency" and "parallelism". In the words of Rob Pike: Concurrency is not Parallelism

    Goroutines are much more lightweight than OS threads and they are managed in "userland" (within the Go process) as opposed to the operating system. Some programs have many thousands (even tens of thousands) of goroutines running, whilst there would certainly be far fewer operating system threads allocated. (This is one of Go's major strengths in asynchronous programs with many routines)

    Because your program is so simple, and the channel buffered, it does not block on writing to the channel:

    c <- x
    

    The fibonacci goroutine isn't getting preempted before it completes the short loop.

    Even the fmt.Println("here") doesn't deterministically introduce preemption - I learned something myself there in writing this answer. It is buffered, like the analagous printf and scanf from C. (see the source code https://github.com/golang/go/blob/master/src/fmt/print.go)

    For interest, if you wanted to artificially control the number of OS threads, you can set the GOMAXPROCS environment variable on the command line:

    ~$ GOMAXPROCS=1 go run main.go
    

    However, with your simple program there probably would be no discernable difference, because the Go runtime is still perfectly capable of scheduling many goroutines against 1 OS thread.

    For example, here is a minor variation to your program. By making the channel buffer smaller (5), but still iterating 10 times, we introduce a point at which the fibonacci go routine can (but won't necessarily) be preempted, where it could block at least once on writing to the channel:

    package main
    
    import (
        "fmt"
    )
    
    func fibonacci(n int, c chan int) {
        x, y := 0, 1
        for i := 0; i < n; i++ {
            c <- x
            x, y = y, x+y
            fmt.Println("here")
        }
        close(c)
    }
    
    func main() {
        c := make(chan int, 5)
        go fibonacci(cap(c)*2, c)
        for i := range c {
            fmt.Println(i)
        }
    }
    
    ~$ GOMAXPROCS=1 go run main.go
    here
    here
    here
    here
    here
    here
    0
    1
    1
    2
    3
    5
    8
    here
    here
    here
    here
    13
    21
    34
    

    Long explanation here, short explanation is that there are a multitude of reasons that a go routine can temporarily block and those are ideal opportunities for the go scheduler to schedule execution of another go routine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿