【Go channel如何控制goroutine并发执行顺序?】

多个goroutine并发执行时,每一个goroutine抢到处理器的时间点不一致,gorouine的执行本身不能保证顺序。即代码中先写的gorouine并不能保证先执行

思路:使用channel进行通信通知,用channel去传递信息,从而控制并发执行顺序

go 复制代码
package main

import (
    "fmt"
    "sync"
    "time"
)

var wg sync.WaitGroup

func main() {
    ch1 := make(chan struct{}, 1)
    ch2 := make(chan struct{}, 1)
    ch3 := make(chan struct{}, 1)
    ch1 <- struct{}{}
    wg.Add(3)
    start := time.Now().Unix()
    go print("gorouine1", ch1, ch2)
    go print("gorouine2", ch2, ch3)
    go print("gorouine3", ch3, ch1)
    wg.Wait()
    end := time.Now().Unix()
    fmt.Printf("duration:%d\n", end-start)
}

func print(gorouine string, inputchan chan struct{}, outchan chan struct{}) {
    // 模拟内部操作耗时
    time.Sleep(1 * time.Second)
    select {
    case <-inputchan:
        fmt.Printf("%s\n", gorouine)
        outchan <- struct{}{}
    }
    wg.Done()
}
  • 输出:
bash 复制代码
gorouine1
gorouine2
gorouine3
duration:1

本文节选于Go合集《常见面试题汇总》:GOLANG ROADMAP 一个专注Go语言学习、求职的社区。

相关推荐
码途行者1 天前
每天10分钟学Go:第23课 协程(goroutine)
开发语言·后端·golang
利威尔xu1 天前
2026-11-25-Go-panic-recover面试
面试·golang
码途行者1 天前
每天10分钟学Go:第24课 通道-协程之间的传送带
开发语言·后端·golang
codeejun4 天前
每日一Go·MySQL-22、幻读、不可重复读、脏读实战演示
开发语言·mysql·golang
码途行者5 天前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang
利威尔xu5 天前
2026-11-24-Go限流器实战
后端·golang
码途行者5 天前
每天10分钟学Go:第21课 错误
开发语言·后端·golang
码途行者6 天前
每天10分钟学Go:第22课 自定义错误
开发语言·后端·golang
码途行者6 天前
每天10分钟学Go:第20课 泛型
c++·算法·golang
codeejun6 天前
每日一Go·MySQL-20、SQL 性能调优实战总结
sql·mysql·golang