golang worker 池子two
onepackage mainimport ("fmt""log""math/rand""time""github.com/alitto/pond")func main() {// Create a buffered (non-blocking) pool that can scale up to 100 workers// and has a buffer capacity of 1000 ta
·
one
package main
import (
"fmt"
"log"
"math/rand"
"time"
"github.com/alitto/pond"
)
func main() {
// Create a buffered (non-blocking) pool that can scale up to 100 workers
// and has a buffer capacity of 1000 tasks
panicHandler := func(p interface{}) {
fmt.Printf("Task panicked: %v", p)
}
pool := pond.New(5, 5,pond.PanicHandler(panicHandler)) // 第一个参数是worker数量, 第二个是缓冲数量 一般设置成一样的数量pop数据不需要等待
// Submit 1000 tasks
for i := 0; i < 10; i++ {
n := i
pool.Submit(func() {
fmt.Printf("Running task #%d\n", n)
time.Sleep(time.Duration(rand.Intn(10))*time.Second)
panic("test")
})
log.Println("我执行了",i)
}
// Stop the pool and wait for all submitted tasks to complete
pool.StopAndWait()
}
two
package main
import (
"github.com/panjf2000/ants/v2"
"log"
"sync"
"time"
)
func main() {
p, _ := ants.NewPool(10000)
_ = p
var xz string
t := time.Now()
var wg sync.WaitGroup
for i := 0;i <= 2000000;i++ {
wg.Add(1)
p.Submit(func() {
defer wg.Done()
xz = "xuzan"
log.Println("xuzan212222")
})
// 测试对比性能
//go func() {
// defer wg.Done()
// xz = "xuzan"
// log.Println("xuzan212222")
//}()
}
wg.Wait()
elapsed := time.Since(t) // 11.443651666s
log.Println(xz,elapsed)
// ------------------------- worker池子 -----------------------
/* // set 10 to the capacity of goroutine pool and 1 second for expired duration.
p, _ := ants.NewPoolWithFunc(10, func(i interface{}) {
myFunc(i)
wg.Done()
})
defer p.Release()
// Submit tasks one by one.
for i := 0; i < runTimes; i++ {
wg.Add(1)
_ = p.Invoke(int32(i))
}
wg.Wait()
fmt.Printf("running goroutines: %d\n", p.Running())
fmt.Printf("finish all tasks, result is %d\n", sum)*/
}
更多推荐
已为社区贡献2条内容
所有评论(0)