SoFunction
Updated on 2025-03-05

Golang Implementation of two go processes taking turns printing a slice

Problem description:

Two go programs take turns printing a slice.

Golang implementation:

Use two channels, only to judge

package main

import (
 "fmt"
 "sync"
)

// Two go programs take turns printing a slicefunc 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 
 (2)
 go func() {
 for ; i < len(nums) && <-ch1; i++ {
  (nums[i])
  ch2 <- true
 }
 ()
 }()
 go func() {
 for ; <-ch2 && i < len(nums); i++ {
  (nums[i])
  ch1 <- true
 }
 ()
 }()
 ()
}

Notice

To clarify the judgment conditions of the two sub-go processes, you should pay attention to whether to judge the size of i first or whether the pipeline has a value first.

If you are not careful, you will have a deadlock.

Use two channels to pass values

package main

import (
 "fmt"
 "sync"
)

// Two go programs take turns printing a slicefunc 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 
 (2)
 go func() {
 for ; i < numsLen; i++ {
  val := <-ch1
  (val)
  ch2 <- i+1
 }
 ()
 }()
 go func() {
 for ; i < numsLen; i++ {
  val := <- ch2
  (val)
  ch1 <- i+1
 }
 ()
 }()
 ()
}

This is the end of this article about the implementation of golang's two go processes taking turns to print a slice. For more related golang's go processes taking turns to print a slice, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!