本文介绍了在golang中并行处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

给出以下代码:

 包主

导入(
fmt
math / rand
time


func main(){
for i:= 0;我< 3; i ++ {
go f(i)
}

//防止main立即退出
var输入字符串
fmt.Scanln(& input)
}

func f(n int){
for i:= 0;我< 10; i ++ {
dowork(n,i)
amt:= time.Duration(rand.Intn(250))
time.Sleep(time.Millisecond * amt)
}


func dowork(goroutine,loopindex int){
//模拟工作
time.Sleep(time.Second * time.Duration(5))
fmt.Printf(gr [%d]:i =%d \\\
,goroutine,loopindex)
}

我可以假设'dowork'函数会并行执行吗?

这是实现并行性的正确方法还是它更好地使用渠道,并为每个goroutine单独'dowork'工人吗?解决方案

您的代码将同时运行,但不是并行。您可以通过设置 GOMAXPROCS 来并行运行;请参阅以获得一个很好的总结。



目前还不清楚你想要在这里完成什么,但它看起来像是完美实现并发的方式。


Given the following code:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    for i := 0; i < 3; i++ {
        go f(i)
    }

    // prevent main from exiting immediately
    var input string
    fmt.Scanln(&input)
}

func f(n int) {
    for i := 0; i < 10; i++ {
        dowork(n, i)
        amt := time.Duration(rand.Intn(250))
        time.Sleep(time.Millisecond * amt)
    }
}

func dowork(goroutine, loopindex int) {
    // simulate work
    time.Sleep(time.Second * time.Duration(5))
    fmt.Printf("gr[%d]: i=%d\n", goroutine, loopindex)
}

Can i assume that the 'dowork' function will be executed in parallel?

Is this a correct way of achieving parallelism or is it better to use channels and separate 'dowork' workers for each goroutine?

解决方案

Your code will run concurrently, but not in parallel. You can make it run in parallel by setting GOMAXPROCS; see the article http://www.goinggo.net/2014/01/concurrency-goroutines-and-gomaxprocs.html for a good summary.

It's not clear exactly what you're trying to accomplish here, but it looks like a perfectly valid way of achieving concurrency to me.

这篇关于在golang中并行处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:56