Go 实现用两个协程顺序打印奇数和偶数

2023-09-07 20:43:12 浏览数 (1)

方法一:使用无缓冲协程的阻塞机制

代码语言:javascript复制
package main

import (
    "fmt"
    "sync"
)

var POOL = 100

func groutine1(p chan int, group *sync.WaitGroup) {
    defer group.Done()
    for i := 1; i <= POOL; i   {
        p <- i
        if i%2 == 1 {
            fmt.Println("groutine-1:", i)
        }
    }
}

func groutine2(p chan int, group *sync.WaitGroup) {
    defer group.Done()
    for i := 1; i <= POOL; i   {
        <-p
        if i%2 == 0 {
            fmt.Println("groutine-2:", i)
        }
    }
}

func main() {
    msg := make(chan int)
    var s sync.WaitGroup
    s.Add(2)
    go groutine1(msg, &s)
    go groutine2(msg, &s)
    s.Wait()

}

方法二 使用全局变量

代码语言:javascript复制
package test

import (
	"fmt"
	"testing"
)

func TestChannel(t *testing.T) {
	nowValue := -1
	nMax := 100
	nChan := make(chan int, 2)
	//输出奇数
	go func() {
		for i := 0; i <= nMax && i%2 == 0; {
			if i-1 == nowValue {
				nChan <- i
				i  = 2
			}
		}
	}()
	//输出偶数
	go func() {
		for i := 1; i <= nMax && i%2 != 0; {
			if i-1 == nowValue {
				nChan <- i
				i  = 2
			}
		}
	}()
	for nowValue < nMax {
		nowValue = <-nChan
		fmt.Println(nowValue)
	}
}
go

0 人点赞