SoFunction
Updated on 2025-03-02

Detailed explanation of Go's method of printing odd and even numbers within 100 alternately with two coroutines

Method 1 (Use unbuffered channel)

package main
import (
	"fmt"
	"time"
)
var flagChan = make(chan int)
func wokr1() {
	for i := 1; i <= 100; i++ {
		flagChan <- 666 //Put in		if i%2 == 1 {
			("Coeisure 1 print:", i)
		}
	}
}
func wokr2() {
	for i := 1; i <= 100; i++ {
		_ = <-flagChan // take out		if i%2 == 0 {
			("Coecho 2 print:", i)
		}
	}
}
func main() {
	go wokr1()
	go wokr2()
	(3 * ) // You can control the exit of the main coroutine through or another channel}

Two coroutines and one channel, use this unbuffered channel as a lock (plays a blocking effect)

Or use the closure method as follows (same as above)

package main
import (
	"fmt"
	"time"
)
func main() {
	c := make(chan int)
	go func() {
		for i := 1; i < 101; i++ {
			c <- 666
			//odd number			if i%2 == 1 {
				("Coeisure 1 print:", i)
			}
		}
	}()
	go func() {
		for i := 1; i < 101; i++ {
			<-c
			//even			if i%2 == 0 {
				("Coecho 2 print:", i)
			}
		}
	}()
	(3 * )
}

Method 2 (set GOMAXPROCS=1)

package main
import (
	"fmt"
	"runtime"
	"time"
)
func main() {
	//Set the number of CPU cores that can be used simultaneously to 1	(1)
	go func() {
		for i := 1; i < 101; i++ {
			//odd number			if i%2 == 1 {
				("Coeisure 1 print:", i)
			}
			//Give up CPU			()
		}
	}()
	go func() {
		for i := 1; i < 101; i++ {
			//even			if i%2 == 0 {
				("Coecho 2 print:", i)
			}
			//Give up CPU			()
		}
	}()
	(3 * )
}

This way we can figure out how *(1) and ()* are used

Alternately print the values ​​of odd and even elements in a slice

package main
import (
	"fmt"
	"time"
)
func main() {
	sli := make([]int, 100)
	for k := 0; k < 100; k++ {
		sli[k] = k * 10
	}
	// Alternately print the values ​​of the odd-even-digit elements in the slice sli	// (len(sli)) //100
	c := make(chan int)
	go func() {
		for i := 0; i < len(sli); i++ {
			c <- 666
			//odd number			if i%2 == 1 {
				("Coeisure 1 print:", sli[i])
			}
		}
	}()
	go func() {
		for i := 0; i < len(sli); i++ {
			<-c
			//even			if i%2 == 0 {
				("Coecho 2 print:", sli[i])
			}
		}
	}()
	(3 * )
}

This is the introduction to this article about the detailed explanation of Go using two coroutines to alternately print odd and even numbers within 100. For more relevant Go coroutines to print odd and even numbers within 100, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!