14.13 在多核心上并行计算

假设我们有 NCPU 个 CPU 核心:const NCPU = 4 //对应一个四核处理器 然后我们想把计算量分成 NCPU 个部分,每一个部分都和其他部分并行运行。

这可以通过以下代码所示的方式完成(我们且省略具体参数)

func DoAll(){
    sem := make(chan int, NCPU) // Buffering optional but sensible
    for i := 0; i < NCPU; i++ {
        go DoPart(sem)
    }
    // Drain the channel sem, waiting for NCPU tasks to complete
    for i := 0; i < NCPU; i++ {
        <-sem // wait for one task to complete
    }
    // All done.
}

func DoPart(sem chan int) {
    // do the part of the computation
    sem <-1 // signal that this piece is done
}

func main() {
    runtime.GOMAXPROCS(NCPU) // runtime.GOMAXPROCS = NCPU
    DoAll()
}

在以上运行模型中,您还需将 GOMAXPROCS 设置为 NCPU(参见 14.1.3)。

链接