并发限制 goroutine 池。
限制任务执行的并发性,而不是排队的任务数。
无论排队多少任务,都不会阻止提交任务。
通过队列支持
golang 工作池公共库
package main
import (
"fmt"
"time"
"github.com/xxjwxc/gowp/workpool"
)
func main() {
wp := workpool.New(10) //设置最大线程数
for i := 0; i < 20; i++ { //开启 20 个请求
ii := i
wp.Do(func() error {
for j := 0; j < 10; j++ { //每次打印 0-10 的值
fmt.Println(fmt.Sprintf("%v->\t%v", ii, j))
time.Sleep(1 * time.Second)
}
//time.Sleep(1 * time.Second)
return nil
})
}
wp.Wait()
fmt.Println("down")
}
package main
import (
"fmt"
"time"
"github.com/xxjwxc/gowp/workpool"
)
func main() {
wp := workpool.New(10) //设置最大线程数
for i := 0; i < 20; i++ { //开启 20 个请求
ii := i
wp.Do(func() error {
for j := 0; j < 10; j++ { //每次打印 0-10 的值
fmt.Println(fmt.Sprintf("%v->\t%v", ii, j))
if ii == 1 {
return errors.Cause(errors.New("my test err")) //有 err 立即返回
}
time.Sleep(1 * time.Second)
}
return nil
})
}
err := wp.Wait()
if err != nil {
fmt.Println(err)
}
fmt.Println("down")
}
package main
import (
"fmt"
"time"
"github.com/xxjwxc/gowp/workpool"
)
func main() {
wp := workpool.New(5) //设置最大线程数
for i := 0; i < 10; i++ { //开启 20 个请求
// ii := i
wp.Do(func() error {
for j := 0; j < 5; j++ {
//fmt.Println(fmt.Sprintf("%v->\t%v", ii, j))
time.Sleep(1 * time.Second)
}
return nil
})
fmt.Println(wp.IsDone())//判断是否完成
}
wp.Wait()
fmt.Println(wp.IsDone())
fmt.Println("down")
}
package main
import (
"fmt"
"time"
"github.com/xxjwxc/gowp/workpool"
)
func main() {
wp := workpool.New(5) //设置最大线程数
for i := 0; i < 10; i++ { //开启 20 个请求
ii := i
wp.DoWait(func() error {
for j := 0; j < 5; j++ {
fmt.Println(fmt.Sprintf("%v->\t%v", ii, j))
// if ii == 1 {
// return errors.New("my test err")
// }
time.Sleep(1 * time.Second)
}
return nil
//time.Sleep(1 * time.Second)
//return errors.New("my test err")
})
}
err := wp.Wait()
if err != nil {
fmt.Println(err)
}
fmt.Println("down")
}
1
mcfog 2020-01-02 19:28:35 +08:00
|
3
whoami9894 2020-01-02 20:13:44 +08:00
@xie1xiao1jun
不是我杠啊,select+channel 和 wg 之间还有啥新旧技术之分吗 |
4
xxjwxc OP @whoami9894 select+channel 模式是会阻塞的(超过最大缓冲数)。
|
5
mengzhuo 2020-01-02 22:14:26 +08:00
@xie1xiao1jun 然后放个链表里不就好了……
|