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 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)