为什么我所谓的并行go程序不并行 [英] Why is my supposedly parallel go program not parallel
问题描述
package main
import (
"fmt"
"runtime"
"sync"
)
var wg sync.WaitGroup
func alphabets() {
for char := 'a'; char < 'a'+26; char++ {
fmt.Printf("%c ", char)
}
wg.Done() //decrement number of goroutines to wait for
}
func numbers() {
for number := 1; number < 27; number++ {
fmt.Printf("%d ", number)
}
wg.Done()
}
func main() {
runtime.GOMAXPROCS(2)
wg.Add(2) //wait for two goroutines
fmt.Println("Starting Go Routines")
go alphabets()
go numbers()
fmt.Println("\nWaiting To Finish")
wg.Wait() //wait for the two goroutines to finish executing
fmt.Println("\nTerminating Program")
}
我希望输出结果混合起来(因为缺少一个更好的词),但是相反;示例输出为:
I expect the output to be mixed up(for lack of a better word), but instead; a sample output is:
$去运行parallel_prog.go
$ go run parallel_prog.go
开始执行例程 等待完成 a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 23 25 25 26 终止程序
Starting Go Routines Waiting To Finish a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Terminating Program
我想念的是什么?
谢谢
推荐答案
您一无所获.工作正常呼叫不是交错"显示(混合),不是因为它们没有并行化,而是因为它们发生的速度非常快.
You're missing nothing. It's working. The calls aren't showing up "interlaced" (mixed up) not because they're not being parallelized, but because they're happening really fast.
您可以轻松地向time.Sleep
添加一些调用,以更好地查看并行化.通过睡眠,我们知道100%应该打印隔行扫描alphabets
和numbers
.
You can easily add some calls to time.Sleep
to see the parallelization better. By sleeping, we know 100% that printing alphabets
and numbers
should be interlaced.
package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func alphabets() {
defer wg.Done()
for char := 'a'; char < 'a'+26; char++ {
fmt.Printf("%c ", char)
time.Sleep(time.Second * 2)
}
}
func numbers() {
defer wg.Done()
for number := 1; number < 27; number++ {
fmt.Printf("%d ", number)
time.Sleep(time.Second * 3)
}
}
func main() {
fmt.Println("Starting Go Routines")
wg.Add(2)
go alphabets()
go numbers()
fmt.Println("\nWaiting To Finish")
wg.Wait()
fmt.Println("\nTerminating Program")
}
注意
您可能已经知道这一点,但是设置GOMAXPROCS
并不会影响此示例是否并行执行,只会消耗多少资源.
Note
You probably already know this, but setting GOMAXPROCS
doesn't have any effect on whether or not this example is executed in parallel, just how many resources it consumes.
GOMAXPROCS设置控制有多少操作系统线程尝试同时执行代码.例如,如果GOMAXPROCS为4,则即使有1000个goroutine,该程序也只能一次在4个操作系统线程上执行代码.该限制不包括系统调用(例如I/O)中阻塞的线程.
The GOMAXPROCS setting controls how many operating systems threads attempt to execute code simultaneously. For example, if GOMAXPROCS is 4, then the program will only execute code on 4 operating system threads at once, even if there are 1000 goroutines. The limit does not count threads blocked in system calls such as I/O.
这篇关于为什么我所谓的并行go程序不并行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!