golang高效安全并发执行函数工具插件库conexec的使用
Golang高效安全并发执行函数工具插件库conexec的使用
简介
conexec是一个并发工具包,用于以高效安全的方式并发执行函数。它支持设置整体超时时间以避免阻塞。
使用方法
通常可以将其设置为单例以节省内存。以下是使用示例:
普通执行器(Actuator)
Actuator是用于并发执行函数的基础结构。
opt := &Options{TimeOut: DurationPtr(time.Millisecond * 50)}
c := NewActuator(opt)
err := c.Exec(
func() error {
fmt.Println(1)
time.Sleep(time.Second * 2)
return nil
},
func() error {
fmt.Println(2)
return nil
},
func() error {
time.Sleep(time.Second * 1)
fmt.Println(3)
return nil
},
)
if err != nil {
// 处理错误
}
池化执行器(Pooled Actuator)
池化执行器使用goroutine池来执行函数,在某些情况下这是一种更高效的方式。
opt := &Options{TimeOut: DurationPtr(time.Millisecond * 50)}
c := NewPooledActuator(5, opt)
err := c.Exec(...)
if err != nil {
// 处理错误
}
使用自定义goroutine池:
c := NewPooledActuator(5).WithPool(pool)
简单使用goroutine执行
done := Exec(...)
if !done {
// 处理未完成情况
}
完整示例
package main
import (
"fmt"
"time"
"github.com/ITcathyh/conexec"
)
func main() {
// 普通执行器示例
normalExample()
// 池化执行器示例
pooledExample()
}
func normalExample() {
opt := &conexec.Options{TimeOut: conexec.DurationPtr(time.Millisecond * 50)}
c := conexec.NewActuator(opt)
err := c.Exec(
func() error {
fmt.Println("Task 1 started")
time.Sleep(time.Millisecond * 30)
fmt.Println("Task 1 completed")
return nil
},
func() error {
fmt.Println("Task 2 started")
time.Sleep(time.Millisecond * 20)
fmt.Println("Task 2 completed")
return nil
},
)
if err != nil {
fmt.Printf("Error occurred: %v\n", err)
}
}
func pooledExample() {
opt := &conexec.Options{TimeOut: conexec.DurationPtr(time.Millisecond * 100)}
c := conexec.NewPooledActuator(3, opt)
err := c.Exec(
func() error {
fmt.Println("Pooled Task 1 started")
time.Sleep(time.Millisecond * 50)
fmt.Println("Pooled Task 1 completed")
return nil
},
func() error {
fmt.Println("Pooled Task 2 started")
time.Sleep(time.Millisecond * 30)
fmt.Println("Pooled Task 2 completed")
return nil
},
func() error {
fmt.Println("Pooled Task 3 started")
time.Sleep(time.Millisecond * 70)
fmt.Println("Pooled Task 3 completed")
return nil
},
)
if err != nil {
fmt.Printf("Pooled Error occurred: %v\n", err)
}
}
这个示例展示了如何使用conexec库来并发执行多个任务,包括普通执行器和池化执行器的用法。
更多关于golang高效安全并发执行函数工具插件库conexec的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复