go协程+管道简单案例

package main

import (
	_ "a1/utils"
	"fmt"
	_ "time"
)

func writeData(initChan chan int) {
	for i := 1; i <= 50; i++ {
		initChan <- i
		fmt.Printf("writeData=%v\n", i)
		//time.Sleep(time.Second)
	}
	close(initChan)
}

func readData(initChan chan int, exitChan chan bool) {
	for {
		v, ok := <-initChan
		if !ok {
			break
		}
		fmt.Printf("readData=%v\n", v)
	}

	// readData 读取完数据后,即任务完成
	exitChan <- true
	close(exitChan)
}

func main() {

	intChan := make(chan int, 50)
	exitChan := make(chan bool, 1)

	go writeData(intChan)
	go readData(intChan, exitChan)

	// time.Sleep(time.Second * 11)

	for{
		_,ok := <-exitChan
		if !ok{
			break
		}
	}
}

你可能感兴趣的:(go,golang,开发语言)