Go实现线程池
来源:互联网 发布:手机模板源码 编辑:程序博客网 时间:2024/06/15 04:14
本文通过代码讲解如何实现一个线程池。代码及注释如下:
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
27
28
29
30
31
32
33
34
35
36
37
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
27
28
29
30
31
32
33
34
35
36
37
package main
import "fmt"
import "time"
//这个是工作线程,处理具体的业务逻辑,将jobs中的任务取出,处理后将处理结果放置在results中。
func worker(id int, jobs<-chan int, results chan<-int) {
for j := range jobs {
fmt.Println("worker", id,"processing job", j)
time.Sleep(time.Second)
results <- j * 2
}
}
func main() {
//两个channel,一个用来放置工作项,一个用来存放处理结果。
jobs := make(chan int, 100)
results := make(chan int, 100)
// 开启三个线程,也就是说线程池中只有3个线程,实际情况下,我们可以根据需要动态增加或减少线程。
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
// 添加9个任务后关闭Channel
// channel to indicate that's all the work we have.
for j := 1; j <= 9; j++ {
jobs <- j
}
close(jobs)
//获取所有的处理结果
for a := 1; a <= 9; a++ {
<-results
}
}
import "fmt"
import "time"
//这个是工作线程,处理具体的业务逻辑,将jobs中的任务取出,处理后将处理结果放置在results中。
func worker(id int, jobs<-chan int, results chan<-int) {
for j := range jobs {
fmt.Println("worker", id,"processing job", j)
time.Sleep(time.Second)
results <- j * 2
}
}
func main() {
//两个channel,一个用来放置工作项,一个用来存放处理结果。
jobs := make(chan int, 100)
results := make(chan int, 100)
// 开启三个线程,也就是说线程池中只有3个线程,实际情况下,我们可以根据需要动态增加或减少线程。
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
// 添加9个任务后关闭Channel
// channel to indicate that's all the work we have.
for j := 1; j <= 9; j++ {
jobs <- j
}
close(jobs)
//获取所有的处理结果
for a := 1; a <= 9; a++ {
<-results
}
}
输出结果:
worker 1 processing job 1
worker 2 processing job 2
worker 3 processing job 3
worker 1 processing job 4
worker 3 processing job 5
worker 2 processing job 6
worker 1 processing job 7
worker 2 processing job 8
worker 3 processing job 9
从中可以看出,多个线程轮流处理了9个任务。
通过这个例子,我们可以学习到:
1、GO中多线程应用开发非常简单。
2、Channel是不同线程间数据交互的利器。 上面的例子中,主线程向jobs中写数据,三个工作线程同时从一个Channel中取数据。
0 0
- Go实现线程池
- Go语言实现线程安全访问队列
- <9> go worker线程池
- Go 并发 、并行、线程池
- Go之简单线程池(引)
- go 线程同步
- Go线程测试
- go之多线程
- Go语言 线程简单读写
- 睡眠排序--go实现
- go实现留言本
- go内部实现
- go channel实现
- [Go]简易聊天实现
- [Go]网络代理实现
- go Stack 简单实现
- go的websocket实现
- go的接口实现
- [阶段二]Android UI列表组件
- 森林_ssl1703_dfs+凸包
- HTML <base> 标签
- C#之WinForm基础 主窗体在哪里可以看到,如何更改主窗体,主窗体有什么特殊的地方
- Linux基础知识
- Go实现线程池
- android can not resolve the symbol r解决
- Java -- 泛型表达式和泛型方法调用中的类型擦除(三)
- Longest Palindromic Substring
- C语言的整型溢出问题(未看)
- Git与GitHub使用
- 获取鼠标划过的控件
- Quick NSQ Cluster
- tjut 3609