douzhi1972 2014-09-16 15:26
浏览 22

使用`make`进行并发内存分配?

I am going to read a large csv file and return an array of structs. So, I decided to split the large file into multiple smaller files with 1 million lines each and use go routines to process them in parallel.

Inside each worker, I create an array to insert the file lines in:

for i := 0; i < 10 ; i++ {
    go func(index int) {
        lines := make([]MyStruct, 1000000)
    }(i)
}

It seems like the go routines wait for each other on this line. So, if the memory allocation for the array takes 1 second, 10 concurrent routines doing that will take 10 seconds, instead of 1 second!

Could you please help me understand why? If this is so, I guess I will allocate memory before starting the go routines and pass the array's pointer to each of them, plus the index of the element that they need to start with while reading lines and setting values.

  • 写回答

1条回答 默认 最新

  • doz95923 2014-09-16 15:31
    关注

    You need to set runtime.GOMAXPROCS(runtime.NumCPU()) or GOMAXPROCS environment variable for it to actually use multiple cores.

    ref: http://golang.org/pkg/runtime/#GOMAXPROCS

    And to quote @siritinga:

    And of course, you need to do something with lines.

    Right now, they are allocated and then lost for the garbage collector.

    A different approach is to preallocate the slice then pass parts of it to the goroutines, for example:

    N := 1000000
    lines := make([]MyStruct, N * 10)
    for i := 0; i < 10 ; i++ {
        idx := i * N
        go func(lines []MyStruct) {
            //do stuff with lines
        }(lines[idx:idx+N])
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥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的速度时间图像)我想问线路信息是什么