Home  >  Article  >  Backend Development  >  Can Golang use multi-core CPU?

Can Golang use multi-core CPU?

angryTom
angryTomOriginal
2020-03-17 16:19:233242browse

Can Golang use multi-core CPU?

Can Golang use multi-core CPU?

Golang can use multi-core CPU. Go has natural support for multi-core programming, so under what circumstances should we use multi-core to accelerate the program?

Related recommendations: golang tutorial

Let’s look at the following program:

package main
import (
        "runtime"
        "fmt"
        "sync"
  "time"
)
//定义任务队列
var waitgroup sync.WaitGroup
func xtgxiso(num int) {
        for i:=1;i<=1000000000;i++{
    num = num+i
    num = num-i
    num = num*i
    num = num/i
  }
        waitgroup.Done() //任务完成,将任务队列中的任务数量-1,其实.Done就是.Add(-1)
}
func main() {
  //记录开始时间
  start := time.Now()
        //设置最大的可同时使用的CPU核数和实际cpu核数一致
        runtime.GOMAXPROCS(1)
        for i := 1; i <= 10; i++ {
                waitgroup.Add(1) //每创建一个goroutine,就把任务队列中任务的数量+1
                go xtgxiso(i)
        }
        waitgroup.Wait() //Wait()这里会发生阻塞,直到队列中所有的任务结束就会解除阻塞 //记录结束时间
  end :=  time.Now()
  //输出执行时间,单位为秒。
  fmt.Println(end.Sub(start).Seconds())
}

We can set it through “runtime.GOMAXPROCS(1)” Single-core or multi-core execution, the comparison results show that multi-core is obviously faster than single-core, so for the operation of the CPU, the acceleration effect of multi-core operation is very obvious.

PHP Chinese website, a large number of programming tutorials, database management toolsnavicat tutorial, welcome to learn!

The above is the detailed content of Can Golang use multi-core CPU?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn