天天看点

Go:协程循环打印循环打印

循环打印

Go语言协程实现两个函数循环打印1到10

package main

import (
	"fmt"
	"sync"
)

func main() {
	sw := make(chan bool)
	defer close(sw)
	times := 10
	wga := sync.WaitGroup{}
	wgb := sync.WaitGroup{}
	wga.Add(times)
	wgb.Add(times)
	go testPrintWithGoroutineA(times, sw, &wga)
	go testPrintWithGoroutineB(times, sw, &wgb)
	sw <- true
	wga.Wait()
	wgb.Wait()
	<-sw
}

func testPrintWithGoroutineA(times int, sw chan bool, wg *sync.WaitGroup) {
	var s bool
	for i := 0; i < times; {
		select {
		case s = <-sw:
			if s {
				wg.Done()
				i++
				fmt.Print("this is func a:")
				for j := 0; j < 10; j++ {
					fmt.Print(j)
				}
				fmt.Println("")
				sw <- !s
			} else {
				sw <- s
			}
		default:
			//
		}
	}
}

func testPrintWithGoroutineB(times int, sw chan bool, wg *sync.WaitGroup) {
	var s bool
	for i := 0; i < times; {
		select {
		case s = <-sw:
			if !s {
				wg.Done()
				i++
				fmt.Print("this is func b:")
				for j := 0; j < 10; j++ {
					fmt.Print(j)
				}
				fmt.Println("")
				sw <- !s
			} else {
				sw <- s
			}
		default:
			//
		}
	}
}