ZBLOG

用 golang 语言来修改

以下是使用 Go 语言重写的代码:

  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. type Task struct {
  7. f func() error
  8. }
  9. type ThreadPool struct {
  10. maxWorkers int
  11. taskQueue chan Task
  12. wg sync.WaitGroup
  13. }
  14. func NewThreadPool(maxWorkers int) *ThreadPool {
  15. return &ThreadPool{
  16. maxWorkers: maxWorkers,
  17. taskQueue: make(chan Task),
  18. }
  19. }
  20. func (tp *ThreadPool) Start() {
  21. for i := 0; i < tp.maxWorkers; i++ {
  22. go tp.worker()
  23. }
  24. }
  25. func (tp *ThreadPool) Submit(f func() error) {
  26. tp.wg.Add(1)
  27. task := Task{f}
  28. select {
  29. case tp.taskQueue <- task:
  30. // submitted successfully
  31. default:
  32. // queue is full, block until there's room
  33. tp.taskQueue <- task
  34. }
  35. }
  36. func (tp *ThreadPool) Shutdown() {
  37. close(tp.taskQueue)
  38. // wait for all workers to complete their tasks and exit gracefully
  39. tp.wg.Wait()
  40. }
  41. func (tp *ThreadPool) worker() {
  42. defer tp.wg.Done()
  43. for task := range tp.taskQueue {
  44. if err := task.f(); err != nil {
  45. fmt.Printf("Error: %v\n", err)
  46. break
  47. }
  48. }
  49. }

NewThreadPool 函数中,我们创建了一个包含最大工作线程数和任务队列的结构体,并返回它。

Start 方法中,我们启动了指定数量的工作线程。每个工作线程都将从任务队列中取出任务并执行它们。

Submit 方法中,我们首先将任务包装成一个 Task 对象,并使用 sync.WaitGroup 来跟踪正在运行的任务数量。然后,我们尝试将任务放入队列中,如果队列已满,则会阻塞直到有空间可用为止。

Shutdown 方法中,我们关闭了任务队列,这会使所有工作线程停止处理新的任务并退出。然后,我们使用 WaitGroup 等待所有正在运行的任务完成并退出。

worker 方法中,我们从任务队列中获取任务并执行它们。如果执行过程中出现错误,则直接打印错误信息并退出整个池。

请注意,在 Go 中没有办法通过异常来终止函数的执行。相反,我们必须显式检查每个操作是否成功,并在失败时采取适当的措施。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=4914

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?