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 <- struct{}{} (3) go printA(&wg, chanA, chanB) go printB(&wg, chanB, chanC) go printC(&wg, chanC, chanA) () } func printA(wg *, chanA, chanB chan struct{}) { defer () for i := 0; i < count; i++ { <-chanA ("A") chanB <- struct{}{} } } func printB(wg *, chanB, chanC chan struct{}) { defer () for i := 0; i < count; i++ { <-chanB ("B") chanC <- struct{}{} } } func printC(wg *, chanC, chanA chan struct{}) { defer () for i := 0; i < count; i++ { <-chanC ("C") chanA <- 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 <- 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 <-(): ("cancel by parent") //No output return case <-chanA: ("A") chanB <- struct{}{} } } } func printB(ctx , chanB, chanC chan struct{}) { for { select { case <-(): ("cancel by parent") //No output return case <-chanB: ("B") chanC <- struct{}{} } } } func printC(ctx , chanC, chanA chan struct{}) { for { select { case <-(): ("cancel by parent") //No output return case <-chanC: ("C") chanA <- 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.