Golang:如何验证运行Go程序的处理器数量 [英] Golang: how to verify number of processors on which a Go program is running

查看:108
本文介绍了Golang:如何验证运行Go程序的处理器数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Go Go(Golang)的新手。我的问题与这篇文章有关 runtime.Gosched究竟做了什么?。代码的结构如下所示。我的问题是,当我更改GOMAXPROCS中的处理器数量时,如何验证它运行的处理器数量。当我做'顶部'时,它会显示a.out流程,即使GOMAXPROCS超过1,也会消耗100%或更少的资源。我将非常感谢您的帮助。

<$ (
fmt
运行时
同步
$ b)

$
$ b var wg sync.WaitGroup

func doTasks(){
fmt.Println(做任务)
for ji:= 1; ji<亿; ji ++ {
for io:= 1; io< 10; io ++ {
//一些计算
}
}
runtime.Gosched()

wg.Done()
}

func main(){
wg.Add(1)
runtime.GOMAXPROCS(1)//或2或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
}


I am new to Google Go (Golang). My question is related to this post What exactly does runtime.Gosched do?. The structure of code is as copied below. My question, is that when I change the number of processor in GOMAXPROCS, how do I verify how many processors it is running on. When I do 'top', it shows a.out process which consumes 100% or less resources even when GOMAXPROCS is more than 1. I would be grateful for your help.

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()
}

解决方案

The largest number of logical CPUs the process can be running on at a given time is no more than the minimum of runtime.GOMAXPROCS(0) and runtime.NumCPU().

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

这篇关于Golang:如何验证运行Go程序的处理器数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆