前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Go 语言社区】Golang语言的多核并行化例子

【Go 语言社区】Golang语言的多核并行化例子

作者头像
李海彬
发布2018-03-19 17:45:29
1.3K0
发布2018-03-19 17:45:29
举报
文章被收录于专栏:Golang语言社区Golang语言社区

写了个多核跑程序的例子,从《go语言编程而来》。关键就是runtime.NumCPU()读出cpu核数,runtime.GOMAXPROCS(MULTICORE)控制使用多个cpu核心。据说以后不会这么麻烦。看了一下运行时间,其实没有变快- -可能是因为这种纯加法太简单了,作为一个例子以后需要可以看一下。

代码语言:javascript
复制
package main
import (
        "fmt"
        "runtime"
        "time"
)
const COUNT int = 100
const SIZE int = 300
func main() {
        var num [SIZE]int
        for i := 0; i < COUNT; i++ {
                num[i] = i
        }
        fmt.Println()
        fmt.Printf("result=%d\n", calmul(num[0:]))
}
func calmul(num []int) int {
        t1 := time.Now()
        var MULTICORE int = runtime.NumCPU() //number of core
        runtime.GOMAXPROCS(MULTICORE) //running in multicore
        fmt.Printf("with %d core\n", MULTICORE)
        ch := make(chan int)
        for i := 0; i < MULTICORE; i++ {
                go calsome(i*COUNT/MULTICORE, (i+1)*COUNT/MULTICORE, num[0:], ch)
        } //divide into some parts
        result := 0
        for i := 0; i < MULTICORE; i++ {
                temp := <-ch
                fmt.Printf("multicore #%d result:%d\n", i, temp)
                result += temp
        } //read result of some part from channel,loop will stop after all is read
        t2 := time.Now()
        fmt.Printf("multicore total time:%d\n", t2.Sub(t1))
        return result
}
func calsome(from, to int, num []int, ch chan int) {
        someresult := 0
        for i := from; i < to; i++ {
                someresult += num[i]
        }
        ch <- someresult //put result in channel
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2016-01-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言社区 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档