parallel-processing - Golang : how to verify number of processors on which a Go program is running

标签 parallel-processing go

我是 Google Go (Golang) 的新手。我的问题与这篇文章有关What exactly does runtime.Gosched do? .代码结构复制如下。我的问题是,当我更改 GOMAXPROCS 中的处理器数量时,我如何验证它正在运行多少个处理器。当我执行 'top' 时,它会显示一个消耗 100% 或更少资源的进程,即使 GOMAXPROCS 大于 1。我将非常感谢您的帮助。

package main

import (
    "fmt"
    "runtime"
    "sync"
)

var wg sync.WaitGroup

func doTasks() {
    fmt.Println(" Doing task ")
    for ji := 1; ji < 100000000; ji++ {
        for io := 1; io < 10; io++ {
            //Some computations
        }
    }
    runtime.Gosched()

    wg.Done()
}

func main() {
    wg.Add(1)
    runtime.GOMAXPROCS(1) // or 2 or 4
    go doTasks()
    doTasks()
    wg.Wait()
}

最佳答案

进程在给定时间内可以运行的最大逻辑 CPU 数不超过 runtime.GOMAXPROCS(0) 的最小值和 runtime.NumCPU() .

func MaxParallelism() int {
    maxProcs := runtime.GOMAXPROCS(0)
    numCPU := runtime.NumCPU()
    if maxProcs < numCPU {
        return maxProcs
    }
    return numCPU
}

关于parallel-processing - Golang : how to verify number of processors on which a Go program is running,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13234749/

相关文章:

c++ - Prim 和 Boruvka 的最小生成树算法

Goroutines 不能并行工作

c++ - MPI中点对点通信造成的死锁,使用循环从master发送给children

go - 如何用零填充数字?

arrays - 从另一个变量调用变量名

regex - 如何在 golang 中编写简单的正则表达式?

c - 无法理解 __syncthreads()

c# - 将单线程应用程序迁移到多线程、并行执行、蒙特卡洛模拟

dictionary - 为什么 Golang 不允许 const 映射?

database - GO 打开本地 postgres 连接