golang goroutine顺序输出方式


Posted in Golang onApril 29, 2021

range字符串,使用goroutine打印

因为goroutine随机执行

for _, v := range str {
        go func() {
            fmt.Println(string(v))
        }()
}

输出:

5

5

5

5

5

可以使用chan顺序输出

for  _, c := range str{
        ch := make(chan rune)
        go func(ch <-chan rune) {
            key := <-ch
            fmt.Println(string(key))
        }(ch)
        ch <- c
    }

输出:

1

2

3

4

5

补充:golang goroutine顺序循环打印ABC

分别使用sync.WaitGroup和context

使用sync.WaitGroup, 可控制循环次数

package main
import (
	"fmt"
	"sync"
)
//控制循环次数
var count = 5
func main() {
	wg := sync.WaitGroup{}
	chanA := make(chan struct{}, 1)
	chanB := make(chan struct{}, 1)
	chanC := make(chan struct{}, 1)
	chanA <- struct{}{}
	wg.Add(3)
	go printA(&wg, chanA, chanB)
	go printB(&wg, chanB, chanC)
	go printC(&wg, chanC, chanA)
	wg.Wait()
}
func printA(wg *sync.WaitGroup, chanA, chanB chan struct{}) {
	defer wg.Done()
	for i := 0; i < count; i++ {
		<-chanA
		fmt.Println("A")
		chanB <- struct{}{}
	}
}
func printB(wg *sync.WaitGroup, chanB, chanC chan struct{}) {
	defer wg.Done()
	for i := 0; i < count; i++ {
		<-chanB
		fmt.Println("B")
		chanC <- struct{}{}
	}
}
func printC(wg *sync.WaitGroup, chanC, chanA chan struct{}) {
	defer wg.Done()
	for i := 0; i < count; i++ {
		<-chanC
		fmt.Println("C")
		chanA <- struct{}{}
	}
}

使用context.WithCancel,通过time.Sleep控制打印数量

package main
import (
	"context"
	"fmt"
	"time"
)
func main() {
	chanA := make(chan struct{}, 1)
	chanB := make(chan struct{}, 1)
	chanC := make(chan struct{}, 1)
	chanA <- struct{}{}
	ctx1, cancel1 := context.WithCancel(context.Background())
	ctx2, cancel2 := context.WithCancel(context.Background())
	ctx3, cancel3 := context.WithCancel(context.Background())
	go printA(ctx1, chanA, chanB)
	go printB(ctx2, chanB, chanC)
	go printC(ctx3, chanC, chanA)
	time.Sleep(100 * time.Microsecond)
	cancel1()
	cancel2()
	cancel3()
}
func printA(ctx context.Context, chanA, chanB chan struct{}) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println("cancel by parent") // 不会输出
			return
		case <-chanA:
			fmt.Println("A")
			chanB <- struct{}{}
		}
	}
}
func printB(ctx context.Context, chanB, chanC chan struct{}) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println("cancel by parent") // 不会输出
			return
		case <-chanB:
			fmt.Println("B")
			chanC <- struct{}{}
		}
	}
}
func printC(ctx context.Context, chanC, chanA chan struct{}) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println("cancel by parent") // 不会输出
			return
		case <-chanC:
			fmt.Println("C")
			chanA <- struct{}{}
		}
	}
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持三水点靠木。如有错误或未考虑完全的地方,望不吝赐教。

Golang 相关文章推荐
go语言中切片与内存复制 memcpy 的实现操作
Apr 27 Golang
golang goroutine顺序输出方式
Apr 29 Golang
Go语言 go程释放操作(退出/销毁)
Apr 30 Golang
Golang标准库syscall详解(什么是系统调用)
May 25 Golang
再次探讨go实现无限 buffer 的 channel方法
Jun 13 Golang
Go语言基础知识点介绍
Jul 04 Golang
Go 通过结构struct实现接口interface的问题
Oct 05 Golang
victoriaMetrics库布隆过滤器初始化及使用详解
Apr 05 Golang
Go语言的协程上下文的几个方法和用法
Apr 11 Golang
Golang map映射的用法
Apr 22 Golang
Golang 入门 之url 包
May 04 Golang
golang 在windows中设置环境变量的操作
解决golang在import自己的包报错的问题
golang import自定义包方式
golang 接口嵌套实现复用的操作
Apr 29 #Golang
浅谈Golang 嵌套 interface 的赋值问题
Apr 29 #Golang
Go 实现英尺和米的简单单位换算方式
Apr 29 #Golang
Golang 空map和未初始化map的注意事项说明
You might like
无线电广播与收音机发展的历史回眸
2021/03/02 无线电
PHP新手上路(七)
2006/10/09 PHP
PHP中file_exists使用中遇到的问题小结
2016/04/05 PHP
PHP内存缓存功能memcached示例
2016/10/19 PHP
基于jQuery的淡入淡出可自动切换的幻灯插件打包下载
2010/09/15 Javascript
拖动table标题实现改变td的大小(css+js代码)
2013/04/16 Javascript
jQuery的each终止或跳过示例代码
2013/12/12 Javascript
Jquery中find与each方法用法实例
2015/02/04 Javascript
纯javascript实现简单下拉刷新功能
2015/03/13 Javascript
Bootstrap开关(switch)控件学习笔记分享
2016/05/30 Javascript
使用 NodeJS+Express 开发服务端的简单介绍
2017/04/07 NodeJs
微信小程序三级联动地址选择器的实例代码
2017/07/12 Javascript
javascript实现打砖块小游戏(附完整源码)
2020/09/18 Javascript
[01:31:22]Ti4 循环赛第四日附加赛LGD vs Mouz
2014/07/13 DOTA
Python兔子毒药问题实例分析
2015/03/05 Python
HTML中使用python屏蔽一些基本功能的方法
2017/07/07 Python
rabbitmq(中间消息代理)在python中的使用详解
2017/12/14 Python
100行python代码实现跳一跳辅助程序
2018/01/15 Python
基于Python Numpy的数组array和矩阵matrix详解
2018/04/04 Python
python实现人民币大写转换
2018/06/20 Python
python读取word 中指定位置的表格及表格数据
2019/10/23 Python
HTML5之SVG 2D入门1—SVG(可缩放矢量图形)概述
2013/01/30 HTML / CSS
HTML5实现一个能够移动的小坦克示例代码
2013/09/02 HTML / CSS
连带责任保证书
2014/04/29 职场文书
手术室护士节演讲稿
2014/08/27 职场文书
公司的门卫岗位职责
2014/09/09 职场文书
小学生竞选班干部演讲稿(5篇)
2014/09/12 职场文书
党的群众路线教育实践活动对照检查材料(个人)
2014/09/24 职场文书
2014银行领导班子四风对照检查材料思想汇报
2014/09/25 职场文书
2014年医院科室工作总结
2014/12/20 职场文书
2015年党风廉政建设个人总结
2015/08/18 职场文书
2016幼儿园新学期寄语
2015/12/03 职场文书
领导干部学习三严三实心得体会
2016/01/05 职场文书
粗暴解决CUDA out of memory的问题
2021/05/22 Python
pytorch 两个GPU同时训练的解决方案
2021/06/01 Python
CentOS7环境下MySQL8常用命令小结
2022/06/10 Servers