dongnianwo8289 2016-05-21 18:33
浏览 13
已采纳

简单的Go并发示例

What would be a simple example of concurrency being used to increase execution speed? I've found a number of examples which use parallelism but none that just use concurrency.

  • 写回答

1条回答 默认 最新

  • doubi1713 2016-05-22 04:28
    关注

    Concurrency and parallelism are two related, but different things. The topic is broad, but let me briefly focus here on the speed.

    Concurrency is related to how design and structure a program in a way that, if parallelism can be applied, then the software may run faster.

    For example; if you have a loop such as

    x := []int{1, 2, 3, 4, 5, 6}
    for i := range x {
      x[i] *= x[i];
    }
    

    this program "feels" concurrent, because the read and write instructions that compute the square of each number in the array are logically independent one from the other. So, you could theoretically design your code in a concurrent way, for example by using goroutines:

    x := []int{1, 2, 3, 4, 5, 6}
    for i := range x {
      go func(j int) { x[j] *= x[j]; }(i)
    }
    wait_the_goroutines();
    

    Assume for now that there are no data races in this example, and each update can be done independently. Well, the update of those values could be made in parallel, because the concurrent design allows it. With the old code, the update is serial by design.

    Parallelism comes in when the computer (CPU, GPU, etc) is able to process multiple instructions at once, in the exact same time. If you have one core in your computer, the goroutines above are unlikely executed in parallel. If you have multiple cores, they may be executed in parallel - because they can be, but you have no actual control on how your computer's parallel hardware is used to execute the code in parallel. That's a task for the go runtime.

    In some sense, concurrency is not used to increase execution speed: parallelism is. Concurrency is used to allow correct parallelization of code.

    Therefore, you cannot really get such example, because even if you can get a "very concurrent" code, the execution speed is bounded to two things:

    1. how much you can parallelize
    2. how the go runtime will schedule the goroutines.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类