Go启动10个goroutine处理任务的例子

Go语言启动10个goroutine处理任务的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
"fmt"
"time"
)

func main() {
channels := make([]chan int, 10)

for i := 0; i < 10; i++ {
channels[i] = make(chan int)
go process(channels[i])
}

for i, ch := range channels {
<-ch
fmt.Println("routine:", i, "quit")
}
}

func process(ch chan int) {
// 模拟处理任务
time.Sleep(time.Second)
ch <- 1
}

输出

1
2
3
4
5
6
7
8
9
10
routine: 0 quit
routine: 1 quit
routine: 2 quit
routine: 3 quit
routine: 4 quit
routine: 5 quit
routine: 6 quit
routine: 7 quit
routine: 8 quit
routine: 9 quit