Golang:为什么 goroutines 不会并行运行?

huangapple go评论93阅读模式
英文:

Golang: Why are goroutines not running in parallel?

问题

我有以下示例,其中两个goroutine应该并行运行。但是,如果你检查输出,你会发现第二个goroutine只有在第一个goroutine完成后才运行。所以,它是顺序执行的。

即使添加了2个处理器:**runtime.GOMAXPROCS(2)**也没有帮助。我在一台具有8个核心的Mac Pro上运行,这绝对不是硬件问题。
所以我的问题是- Golang真的是并行的吗?如何使下面的示例并行运行?

输出:

Thread 1
Thread 1
  …………....
Thread 1
Thread 1
Thread 2
Thread 2
  …………....
Thread 2
Thread 2

Go代码:

package main

import (
    "runtime"
    "time"
)

func main() {

    runtime.GOMAXPROCS(2)

    go func() {
        for i := 0; i < 100; i++ {
            println("Thread 1")
            //time.Sleep(time.Millisecond * 10)
        }
    }()

    go func() {
        for i := 0; i < 100; i++ {
            println("Thread 2")
            //time.Sleep(time.Millisecond * 10)
        }
    }()

    time.Sleep(time.Second)
}
英文:

I have the following example below where two goroutine should be running in parallel. But if you check the output, the second goroutine only runs after the first goroutine completes. So, it's sequential.

Adding 2 processors: runtime.GOMAXPROCS(2) also didn't help. I'm running on a Mac pro with 8 cores and it is definitely not a hardware issue.
So my question - Is Golang really parallel and how to make example below run in
parallel?

Output:

Thread 1
Thread 1
  …………....
Thread 1
Thread 1
Thread 2
Thread 2
  …………....
Thread 2
Thread 2

Go code:

package main

import (
    &quot;runtime&quot;
    &quot;time&quot;
)

func main() {

    runtime.GOMAXPROCS(2)

    go func() {
        for i := 0; i &lt; 100; i++ {
            println(&quot;Thread 1&quot;)
            //time.Sleep(time.Millisecond * 10)
        }
    }()

    go func() {
        for i := 0; i &lt; 100; i++ {
            println(&quot;Thread 2&quot;)
            //time.Sleep(time.Millisecond * 10)
        }
    }()

    time.Sleep(time.Second)
}

答案1

得分: 4

为了判断你的程序是并行还是并发运行,可以通过打印不同的值来观察执行顺序。根据这篇文章:Concurrency, Goroutines and GOMAXPROCS

你的代码无法充分表达并行调用。请参考下面的代码:

package main

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

func main() {
	runtime.GOMAXPROCS(2)

	var wg sync.WaitGroup
	wg.Add(2)

	fmt.Println("Starting Go Routines")
	go func() {
		defer wg.Done()

		//time.Sleep(1 * time.Microsecond)
		for char := 'a'; char < 'a'+26; char++ {
			fmt.Printf("%c ", char)
		}
	}()

	go func() {
		defer wg.Done()

		for number := 1; number < 27; number++ {
			fmt.Printf("%d ", number)
		}
	}()

	fmt.Println("Waiting To Finish")
	wg.Wait()

	fmt.Println("\nTerminating Program")
}

从上面的代码可以看出,使用for循环打印不同的值序列。

如果你注释掉runtime.GOMAXPROCS(2)这一行,并取消注释time.Sleep(1 * time.Microsecond)这一行,输出结果将会不同。

英文:

In order to understand your program is running parallel or concurrently using goroutine is print the different value in sequence.
From this article : Concurrency, Goroutines and GOMAXPROCS .

Your code can't express enough to represent a parallel call. Please see the code below.

package main

import (
	&quot;fmt&quot;
	&quot;runtime&quot;
	&quot;sync&quot;
)

func main() {
	runtime.GOMAXPROCS(2)

	var wg sync.WaitGroup
	wg.Add(2)

	fmt.Println(&quot;Starting Go Routines&quot;)
	go func() {
		defer wg.Done()

		//time.Sleep(1 * time.Microsecond)
		for char := &#39;a&#39;; char &lt; &#39;a&#39;+26; char++ {
			fmt.Printf(&quot;%c &quot;, char)
		}
	}()

	go func() {
		defer wg.Done()

		for number := 1; number &lt; 27; number++ {
			fmt.Printf(&quot;%d &quot;, number)
		}
	}()

	fmt.Println(&quot;Waiting To Finish&quot;)
	wg.Wait()

	fmt.Println(&quot;\nTerminating Program&quot;)
}

As you can see from the above code print the different value sequence using for loop.

The output would be different if you comment the runtime.GOMAXPROCS(2) and uncomment the line on time.Sleep(1 * time.Microsecond).

huangapple
  • 本文由 发表于 2017年5月18日 13:24:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/44039223.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定