concurrency - 为什么我所谓的并行 go 程序不是并行的

标签 concurrency go parallel-processing

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")
}

我希望输出会混淆(因为缺少更好的词),但是相反;示例输出是:

$ 去运行 parallel_prog.go

开始 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 24 25 26 终止程序

我错过了什么?

谢谢,

最佳答案

你什么都不缺。它的工作。调用没有显示为“交错”(混合),不是因为它们没有并行化,而是因为它们发生的非常快

您可以轻松地添加一些对 time.Sleep 的调用以更好地查看并行化。通过 sleep ,我们 100% 知道打印 alphabetsnumbers 应该是交错的。

你的Sleep调用“强制”隔行扫描的程序

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 对这个例子是否并行执行没有任何影响,只是它消耗了多少资源。

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 1.5 GOMAXPROCS Default

关于concurrency - 为什么我所谓的并行 go 程序不是并行的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31296054/

相关文章:

java - 在并行 Java 流中处理随机数

java - 如何使用 Maven 在所有模块上并行运行单元测试?

Python生成器和set(generator)得到不同的结果

java - RxJava - 调度程序与 ExecutorService?

go - 如何在另一个模块中使用 "GOPATH"之外的模块?

go - 将 JSON 整数解码为空接口(interface)会导致错误的类型断言

interface - 如何获取未知接口(interface)上的结构值{}

java - 跨服务锁定文件

java - ReentrantLock.lock() 不会阻塞其他线程

python - 并行目录遍历 python