gpt4 book ai didi

Go同步和并发模型

转载 作者:IT王子 更新时间:2023-10-29 02:28:17 25 4
gpt4 key购买 nike

我是一名 Go 新手,我正在关注 gobyexample.com学习基础知识。当我到达“关闭 channel ”部分时,教程会插入此代码片段(我将删除原始评论):

    package main

import "fmt"

func main() {
jobs := make(chan int, 5)
done := make(chan bool)

go func() {
for {
j, more := <-jobs
if more {
fmt.Println("received job", j)
} else {
fmt.Println("received all jobs")
done <- true
return
}
}
}()

for j := 1; j <= 18; j++ {
jobs <- j
fmt.Println("sent job", j)
}
close(jobs)
fmt.Println("sent all jobs")

<-done
}

原始代码在作业发送者循环中设置 3 而不是 18。

play.golang.org 中执行此代码这是我不完全理解的。它总是输出以下内容:

sent job 1
sent job 2
sent job 3
sent job 4
sent job 5
received job 1
received job 2
received job 3
received job 4
received job 5
received job 6
sent job 6
sent job 7
sent job 8
sent job 9
sent job 10
sent job 11
sent job 12
received job 7
received job 8
received job 9
received job 10
received job 11
received job 12
received job 13
sent job 13
sent job 14
sent job 15
sent job 16
sent job 17
sent job 18
sent all jobs
received job 14
received job 15
received job 16
received job 17
received job 18
received all jobs

所以我知道 channel 的“队列”(我知道这个术语不是最准确的,但为了学习我自己的目的,这是我对 channel 的理解)的大小为 5 所以前 10 条日志消息对我来说没问题。

但是消息 6 和 13 如何在实际发送之前输出它们的接收信息?如果 channel 大小为 5,如何连续发送 7 条消息?我错过了什么?

最佳答案

Goroutines 并发运行,因此它们也同时打印到标准输出(即乱序)。此外,fmt.Print API 是缓冲的,因此您的打印实际上不会在调用时立即打印。这也发生在其他语言中。

这就是为什么您无法从 stdout 中的消息中导出 goroutine 的真正并发执行。

关于Go同步和并发模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56343626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com