golang两个协程交替打印出1-100

基于channel实现的,两个协程交替打印出1-100

package main

import (
	"fmt"
	"sync"
)

var (
	toOdd  = make(chan struct{})
	toEven = make(chan struct{})
	wg     = sync.WaitGroup{}
)

func main() {
	wg.Add(2)
	go printOdd()
	go printEven()
	wg.Wait()
	fmt.Println("-----done-----")
}

func printOdd() {
	defer wg.Done()
	for i := 1; i <= 100; i += 2 {
		if i != 1 {
			<-toOdd
		}

		fmt.Println(i)

		toEven <- struct{}{}
	}
}

func printEven() {
	defer wg.Done()
	for i := 2; i <= 100; i += 2 {
		<-toEven

		fmt.Println(i)

		if i != 100 {
			toOdd <- struct{}{}
		}
	}
}
posted @ 2022-03-08 17:14  宝树呐  阅读(947)  评论(0编辑  收藏  举报