go语言使用goroutines
和channel
实现一个工作池相当简单。使用goroutines
开指定书目线程,通道分别传递任务和任务结果。简单的线程池代码如下:
package main import "fmt"
import "time" // Here's the worker, of which we'll run several
// concurrent instances. These workers will receive
// work on the `jobs` channel and send the corresponding
// results on `results`. We'll sleep a second per job to
// simulate an expensive task.
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Println("worker", id, "started job", j)
time.Sleep(time.Second)
fmt.Println("worker", id, "finished job", j)
results <- j *
}
} func main() { // In order to use our pool of workers we need to send
// them work and collect their results. We make 2
// channels for this.
jobs := make(chan int, )
results := make(chan int, ) // This starts up 3 workers, initially blocked
// because there are no jobs yet.
for w := ; w <= ; w++ {
go worker(w, jobs, results)
} // Here we send 5 `jobs` and then `close` that
// channel to indicate that's all the work we have.
for j := ; j <= ; j++ {
jobs <- j
}
close(jobs) // Finally we collect all the results of the work.
for a := ; a <= ; a++ {
<-results
}
}
执行上面代码,将得到以下输出结果
worker started job
worker started job
worker started job
worker finished job
worker started job
worker finished job
worker started job
worker finished job
worker finished job
worker finished job
看代码中注释也大概能理解每一步的含义,代码25行和26行分别初始化了2个通道,用于发送任务给子线程和接收子线程计算的任务结果。30-32行代码是启动了3个子线程,用于处理任务,并将任务通道和结果通道传递给了线程函数。36-38行代码是发送任务到jobs通道,工作线程在没有任务时,是阻塞着等待任务,当发现任务通道中有任务时,开始执行任务,当任务执行完毕时,将任务结果发送给结果通道。
jobs <-chan int:只能接收数据
results chan<- int:只能发送数据
如果您觉得文章不错,不妨给个打赏,写作不易,感谢各位的支持。您的支持是我最大的动力,谢谢!!!