golang轻量级goroutine线程池管理插件库go-tools/multithreading的使用

golang轻量级goroutine线程池管理插件库go-tools/multithreading的使用

简介

go-tools/multithreading 是一个专注于并发和goroutine管理的Golang工具库。它提供了ThreadTracker结构体,可以轻松管理goroutine的生命周期。

主要功能包括:

  • 创建新的goroutine
  • 等待所有goroutine完成
  • 设置goroutine完成后执行的deferred函数
  • 通过panic处理器轻松处理goroutine中的panic
  • 停止threadTracker接收新函数
  • 获取当前活跃goroutine的数量

安装

使用以下命令安装:

go get github.com/nikhilsaraf/go-tools/multithreading

导入包:

import "github.com/nikhilsaraf/go-tools/multithreading"

使用示例

下面是一个完整的使用示例:

package main

import (
  "fmt"
  "github.com/nikhilsaraf/go-tools/multithreading"
)

func main() {
  // 创建thread tracker实例
  threadTracker := multithreading.MakeThreadTracker()

  // 启动goroutine
  for i := 0; i < 10; i++ {
    err := threadTracker.TriggerGoroutine(func(inputs []interface{}) {
      // 从inputs中读取传入的值
      // 这是为了将变量"绑定"到这个goroutine
      value := inputs[0].(int)
      
      fmt.Printf("Goroutine #%d\n", value)
    }, []interface{}{i})

    if err != nil {
      panic(err)
    }
  }

  // 等待所有goroutine完成
  threadTracker.Wait()
  fmt.Printf("done\n")
}

示例输出

运行上述代码可能的输出(顺序可能不同):

Goroutine #1
Goroutine #2
Goroutine #9
Goroutine #0
Goroutine #3
Goroutine #7
Goroutine #6
Goroutine #4
Goroutine #8
Goroutine #5
done

更多功能

ThreadTracker还提供以下方法:

// 设置deferred函数,在所有goroutine完成后执行
threadTracker.SetDeferred(func() {
    fmt.Println("All goroutines completed")
})

// 设置panic处理器
threadTracker.SetPanicHandler(func(panic interface{}) {
    fmt.Printf("Recovered from panic: %v\n", panic)
})

// 停止接收新的goroutine
threadTracker.StopAcceptingNew()

// 获取当前活跃goroutine数量
count := threadTracker.ActiveGoroutines()

这个库非常适合需要管理大量goroutine的场景,能够有效控制并发数量和处理goroutine中的异常情况。


更多关于golang轻量级goroutine线程池管理插件库go-tools/multithreading的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang轻量级goroutine线程池管理插件库go-tools/multithreading的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


go-tools/multithreading 轻量级 Goroutine 线程池管理库

go-tools/multithreading 是一个轻量级的 Goroutine 线程池管理库,它提供了简单易用的 API 来管理和控制 Goroutine 的执行。

主要特性

  1. 限制并发 Goroutine 数量
  2. 任务队列管理
  3. 优雅关闭支持
  4. 错误处理机制
  5. 超时控制

安装

go get github.com/go-tools/multithreading

基本使用示例

package main

import (
	"fmt"
	"time"
	
	"github.com/go-tools/multithreading"
)

func main() {
	// 创建一个最大并发数为3的线程池
	pool := multithreading.NewThreadPool(3)
	
	// 提交10个任务
	for i := 0; i < 10; i++ {
		taskID := i
		pool.Submit(func() error {
			fmt.Printf("Task %d started\n", taskID)
			time.Sleep(1 * time.Second) // 模拟耗时操作
			fmt.Printf("Task %d completed\n", taskID)
			return nil
		})
	}
	
	// 等待所有任务完成
	pool.Wait()
	fmt.Println("All tasks completed")
}

高级功能示例

1. 带错误处理的任务

pool := multithreading.NewThreadPool(2)

for i := 0; i < 5; i++ {
	taskID := i
	pool.Submit(func() error {
		if taskID%2 == 0 {
			return fmt.Errorf("error in task %d", taskID)
		}
		time.Sleep(500 * time.Millisecond)
		return nil
	})
}

err := pool.Wait()
if err != nil {
	fmt.Printf("Some tasks failed: %v\n", err)
}

2. 带超时控制的任务

pool := multithreading.NewThreadPool(2).WithTimeout(1 * time.Second)

pool.Submit(func() error {
	time.Sleep(2 * time.Second) // 这个任务会超时
	return nil
})

err := pool.Wait()
if err != nil {
	fmt.Printf("Task timeout: %v\n", err)
}

3. 优雅关闭线程池

pool := multithreading.NewThreadPool(3)

// 提交一些任务
for i := 0; i < 10; i++ {
	taskID := i
	pool.Submit(func() error {
		time.Sleep(500 * time.Millisecond)
		fmt.Printf("Task %d completed\n", taskID)
		return nil
	})
}

// 优雅关闭,等待正在执行的任务完成但不接受新任务
pool.Shutdown()

最佳实践

  1. 合理设置并发数:根据CPU核心数和任务类型设置合适的并发数
  2. 处理错误:始终检查Wait()返回的错误
  3. 资源清理:使用Shutdown()确保所有资源被正确释放
  4. 超时控制:对于可能长时间运行的任务设置超时

性能考虑

  • 对于CPU密集型任务,并发数建议设置为CPU核心数
  • 对于IO密集型任务,可以适当增加并发数
  • 避免在任务中创建大量新对象,以减少GC压力

替代方案比较

相比其他线程池库如antstunnygo-tools/multithreading的优势在于:

  • 更简单的API
  • 更轻量级的实现
  • 内置超时和错误处理

总结

go-tools/multithreading是一个简单高效的Goroutine线程池管理库,适合需要控制并发数的场景。它通过限制并发Goroutine数量来避免资源耗尽,同时提供了任务队列、错误处理和超时控制等实用功能。

对于大多数需要简单并发控制的Go应用来说,这是一个不错的选择。

回到顶部