SoFunction
Updated on 2025-03-01

golang goroutine sequential output method

Range string, print using goroutine

Because goroutine is executed randomly

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

Output:

5

5

5

5

5

Can output sequentially using chan

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

Output:

1

2

3

4

5

Supplement: golang goroutine sequentially loop printing ABC

Use and context separately

Used to control the number of cycles

package main
import (
	"fmt"
	"sync"
)
//Control the number of cyclesvar count = 5
func main() {
	wg := {}
	chanA := make(chan struct{}, 1)
	chanB := make(chan struct{}, 1)
	chanC := make(chan struct{}, 1)
	chanA &lt;- struct{}{}
	(3)
	go printA(&amp;wg, chanA, chanB)
	go printB(&amp;wg, chanB, chanC)
	go printC(&amp;wg, chanC, chanA)
	()
}
func printA(wg *, chanA, chanB chan struct{}) {
	defer ()
	for i := 0; i &lt; count; i++ {
		&lt;-chanA
		("A")
		chanB &lt;- struct{}{}
	}
}
func printB(wg *, chanB, chanC chan struct{}) {
	defer ()
	for i := 0; i &lt; count; i++ {
		&lt;-chanB
		("B")
		chanC &lt;- struct{}{}
	}
}
func printC(wg *, chanC, chanA chan struct{}) {
	defer ()
	for i := 0; i &lt; count; i++ {
		&lt;-chanC
		("C")
		chanA &lt;- struct{}{}
	}
}

Use, control the number of prints

package main
import (
	"context"
	"fmt"
	"time"
)
func main() {
	chanA := make(chan struct{}, 1)
	chanB := make(chan struct{}, 1)
	chanC := make(chan struct{}, 1)
	chanA &lt;- struct{}{}
	ctx1, cancel1 := (())
	ctx2, cancel2 := (())
	ctx3, cancel3 := (())
	go printA(ctx1, chanA, chanB)
	go printB(ctx2, chanB, chanC)
	go printC(ctx3, chanC, chanA)
	(100 * )
	cancel1()
	cancel2()
	cancel3()
}
func printA(ctx , chanA, chanB chan struct{}) {
	for {
		select {
		case &lt;-():
			("cancel by parent") //No output			return
		case &lt;-chanA:
			("A")
			chanB &lt;- struct{}{}
		}
	}
}
func printB(ctx , chanB, chanC chan struct{}) {
	for {
		select {
		case &lt;-():
			("cancel by parent") //No output			return
		case &lt;-chanB:
			("B")
			chanC &lt;- struct{}{}
		}
	}
}
func printC(ctx , chanC, chanA chan struct{}) {
	for {
		select {
		case &lt;-():
			("cancel by parent") //No output			return
		case &lt;-chanC:
			("C")
			chanA &lt;- struct{}{}
		}
	}
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.