golang Implementation of two go procedures that take turns printing a slice

  • 2020-11-20 06:08:03
  • OfStack

Problem description:

Two go processes print one slice in turn.

Golang implementation:

Use two channel, just for judgment


package main

import (
 "fmt"
 "sync"
)

//  two  go  Serial printing 1 A slice 
func main() {
 ch1 := make(chan bool, 1)
 ch2 := make(chan bool, 1)
 ch1 <- true
 nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
 var i int
 var wg sync.WaitGroup
 wg.Add(2)
 go func() {
 for ; i < len(nums) && <-ch1; i++ {
  fmt.Println(nums[i])
  ch2 <- true
 }
 wg.Done()
 }()
 go func() {
 for ; <-ch2 && i < len(nums); i++ {
  fmt.Println(nums[i])
  ch1 <- true
 }
 wg.Done()
 }()
 wg.Wait()
}

Pay attention to

To clarify the judgment conditions of the two subES19en procedures, it is necessary to judge the size of i first or whether the pipe has value first.

A slight mistake can cause a deadlock.

Use two channel to pass values


package main

import (
 "fmt"
 "sync"
)

//  two  go  Serial printing 1 A slice 
func main() {
 ch1 := make(chan int, 1)
 ch2 := make(chan int, 1)
 nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
 ch1 <- nums[0]
 i := 1
 numsLen := len(nums)
 var wg sync.WaitGroup
 wg.Add(2)
 go func() {
 for ; i < numsLen; i++ {
  val := <-ch1
  fmt.Println(val)
  ch2 <- i+1
 }
 wg.Done()
 }()
 go func() {
 for ; i < numsLen; i++ {
  val := <- ch2
  fmt.Println(val)
  ch1 <- i+1
 }
 wg.Done()
 }()
 wg.Wait()
}


Related articles: