douyinzha5820 2018-02-23 09:10
浏览 41
已采纳

渠道与平行主义的困惑

I'm learning myself Golang, and I'm a bit confused about parallelism and how it is implemented in Golang.

Given the following example:

package main

import (
    "fmt"
    "sync"
    "math/rand"
    "time"
)


const (
    workers = 1
    rand_count = 5000000
)


func start_rand(ch chan int) {
    defer close(ch)
    var wg sync.WaitGroup
    wg.Add(workers)
    rand_routine := func(counter int) {
        defer wg.Done()
        for i:=0;i<counter;i++ {
            seed := time.Now().UnixNano()
            rand.Seed(seed)
            ch<-rand.Intn(5000)

        }
    }
    for i:=0; i<workers; i++ {
        go rand_routine(rand_count/workers)
    }
    wg.Wait()
}

func main() {
    start_time := time.Now()
    mychan := make(chan int, workers)
    go start_rand(mychan)
    var wg sync.WaitGroup
    wg.Add(workers)

    work_handler := func() {
        defer wg.Done()
        for {
            v, isOpen := <-mychan
            if !isOpen { break }
            fmt.Println(v)
        }
    }
    for i:=0;i<workers;i++ {
        go work_handler()
    }
    wg.Wait()
    elapsed_time := time.Since(start_time)
    fmt.Println("Done",elapsed_time)
}

This piece of code takes about one minute to run on my Macbook. I assumed that increasing the "workers" constants, would launch additional go routines, and since my laptop has multiple cores, would shorten the execution time.

This is not the case however. Increasing the workers does not reduce the execution time.

I was thinking that setting workers to 1, would create 1 goroutine to generate the random numbers, and setting it to 4, would create 4 goroutines. Given the multicore nature of my laptop, I was expecting that 4 workers would run on different cores, and therefore, increae the performance. However, I see increased load on all my cores, even when workers is set to 1. What am I missing here?

  • 写回答

2条回答 默认 最新

  • doutang1946 2018-02-23 10:22
    关注

    Your code has some issues which makes it inherently slow:

    • You are seeding inside the loop. This needs only to be done once
    • You are using the same source for random numbers. This source is thread safe, but takes away any performance gains for concurrent workers. You could create a source for each worker with rand.New
    • You are printing a lot. Printing is thread safe, too. So that takes away any speed gains for concurrent workers.
    • As Zak already pointed out: The concurrent work inside the go routines is very cheap and the communication is expensive.

    You could rewrite your program like that. Then you will see some speed gains when you change the number of workers:

    package main
    
    import (
        "fmt"
        "math/rand"
        "time"
    )
    
    const (
        workers   = 1
        randCount = 5000000
    )
    
    var results = [randCount]int{}
    
    func randRoutine(start, counter int, c chan bool) {
        r := rand.New(rand.NewSource(time.Now().UnixNano()))
        for i := 0; i < counter; i++ {
            results[start+i] = r.Intn(5000)
        }
        c <- true
    }
    
    func main() {
        startTime := time.Now()
        c := make(chan bool)
    
        start := 0
        for w := 0; w < workers; w++ {
            go randRoutine(start, randCount/workers, c)
            start += randCount / workers
        }
    
        for i := 0; i < workers; i++ {
            <-c
        }
    
        elapsedTime := time.Since(startTime)
        for _, i := range results {
            fmt.Println(i)
        }
        fmt.Println("Time calulating", elapsedTime)
    
        elapsedTime = time.Since(startTime)
        fmt.Println("Toal time", elapsedTime)
    }
    

    This program does a lot of work in a go routine and communicates minimal. Also a different random source is used for each go routine.

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

报告相同问题?

悬赏问题

  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真