比如多文件处理,常用
package patternhandle
import (
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/panjf2000/ants"
)
var sum int32
func myFunc(i interface{}) {
n := i.(int) // 你要处理字符串就转成字符串,比如多文件处理
atomic.AddInt32(&sum, int32(n))
fmt.Printf("run with %d\n", n)
}
func demoFunc() {
time.Sleep(10 * time.Millisecond)
fmt.Println("Hello World!")
// return nil
}
// 两种协程池的开启方式 例子
func ANtt() {
runTimes := 11
// use the common pool
var wg sync.WaitGroup
p1, _ := ants.NewPool(4) // 不设置就是没得默认限制,会以最大的开
for i := 0; i < runTimes; i++ {
wg.Add(1)
p1.Submit(func() {
demoFunc()
wg.Done()
})
}
wg.Wait()
fmt.Printf("running goroutines: %d\n", p1.Running())
fmt.Printf("finish all tasks.\n")
// use the pool with a function
// set 10 the size of goroutine pool
p, _ := ants.NewPoolWithFunc(4, func(i interface{}) {
myFunc(i)
wg.Done()
})
// submit tasks
for i := 0; i < runTimes; i++ {
wg.Add(1)
// p.Serve(i)
p.Invoke(i)
}
wg.Wait()
fmt.Printf("running goroutines: %d\n", p.Running())
p.Release()
fmt.Printf("release gorout running goroutines: %d\n", p.Running())
fmt.Printf("finish all tasks, result is %d\n", sum)
}
测试
func TestANtt(t *testing.T) {
ANtt()
}