Golang

使用channel实现简单并发,注意执行顺序

 1package main
 2
 3import (
 4	"fmt"
 5	"sync"
 6	"time"
 7)
 8
 9var wg sync.WaitGroup
10
11func printer(ch chan int) {
12	for i := range ch {
13		fmt.Printf("Received %d \n", i)
14		<-time.After(time.Second / 5)
15		fmt.Printf("Job %v done \n", i)
16	}
17	println("All Jobs done")
18	wg.Done()
19	println("Finished")
20}
21
22// main is the entry point for the program.
23func main() {
24	c := make(chan int)
25	go printer(c)
26	wg.Add(1)
27
28	// Send 5 integers on the channel.
29	for i := 1; i <= 5; i++ {
30		c <- i
31	}
32	println(">>> Close chan")
33	close(c)
34	println(">>> Closed")
35	wg.Wait()
36}

执行结果如图:

image-20210316003214320