登录
首页 >  Golang >  Go问答

Goroutine 的执行顺序

来源:stackoverflow

时间:2024-03-08 17:51:23 466浏览 收藏

今天golang学习网给大家带来了《Goroutine 的执行顺序》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

问题内容

我现在正在学习golang,在网上发现了一些有趣的教程。例如这个:https://golangbot.com/channels/

在关于 goroutine 的这一部分中,有一个示例案例如下:

package main

import (
    "fmt"
)

func producer(chnl chan int) {
    for i := 0; i < 10; i++ {
        fmt.println("debugging send...", i)
        chnl <- i
    }
    close(chnl)
}
func main() {
    ch := make(chan int)
    go producer(ch)
    for {
        v, ok := <-ch
        if ok == false {
            break
        }
        fmt.println("received ", v, ok)
    }
}

fmt.println("debugging send...", i) 是我出于调试目的而添加的。输出为:

debugging send... 0
debugging send... 1
Received  0 true
Received  1 true
debugging send... 2
debugging send... 3
Received  2 true
Received  3 true
debugging send... 4
debugging send... 5
Received  4 true
Received  5 true
debugging send... 6
debugging send... 7
Received  6 true
Received  7 true
debugging send... 8
debugging send... 9
Received  8 true
Received  9 true

输出顺序对我来说似乎很有趣,但无法完全理解幕后发生的事情。


解决方案


唯一需要同步的地方是通道操作。这些语句之外的 goroutine 中的操作顺序之间不需要存在关联。

多次运行你的程序,我大部分时间都得到了你的输出,但有时我也看到了这样的东西:

debugging send... 0
debugging send... 1
received  0 true
received  1 true
debugging send... 2
debugging send... 3
received  2 true
received  3 true
debugging send... 4
debugging send... 5
received  4 true
received  5 true
debugging send... 6
debugging send... 7
received  6 true
debugging send... 8
received  7 true
received  8 true
debugging send... 9
received  9 true

尝试运行此 bash shell 脚本多次运行该程序并比较其输出:

#!/bin/bash

# c.go has your Go program
go run c.go > first.txt
cat first.txt

echo "======"
while :; do
    go run c.go > run.txt
    if ! diff -q run.txt first.txt; then
        break
    fi
done

cat run.txt

编辑:您可能会发现 https://golang.org/ref/mem 阅读有关 go 中同步的内容很有趣。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>