golang使用协程和管道的例子

1. 协程和管道

package main

import (
	"fmt"
	"time"
)

func write(ch chan int) {
	for i := 0; i < 10; i++ {
		ch <- i
		fmt.Println("write data: ", i)
	}
}

func read(ch chan int) {
	for {
		var b int
		b = <-ch
		fmt.Println("read data: ", b)
		time.Sleep(time.Second)
	}
}

func main() {
	intChan := make(chan int, 5)
	go write(intChan)
	go read(intChan)

	time.Sleep(10 * time.Second)
}

2. 使用 WaitGroup 控制协程

package main

import (
	"fmt"
	"sync"
)

var wg sync.WaitGroup

func write(ch chan int) {
	for i := 0; i < 10; i++ {
		ch <- i
		fmt.Println("write data: ", i)
	}
}

func read(ch chan int) {
	for {
		fmt.Println("read data: ", <-ch)
		wg.Done()
	}
}

func main() {
	ch := make(chan int, 5)
	wg.Add(10)

	go write(ch)
	go read(ch)

	wg.Wait()
}