go 创建携程池,开启并发

摘要:
")}}

地址;https://github.com/panjf2000/ants

采用蚂蚁池开源的SDK,ants 是一个高性能且低损耗的 goroutine 池

package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/panjf2000/ants"
)
var sum int32
func myFunc(i interface{}) {
n := i.(int32)
atomic.AddInt32(&sum, n)
fmt.Printf("run with %d ", n)
}
func demoFunc() {
time.Sleep(10 * time.Millisecond)
fmt.Println("Hello World!")
}
func main() {
defer ants.Release()
runTimes := 1000
// Use the common pool.
var wg sync.WaitGroup
syncCalculateSum := func() {
demoFunc()
wg.Done()
}
for i := 0; i < runTimes; i++ {
wg.Add(1)
_ = ants.Submit(syncCalculateSum)
}
wg.Wait()
fmt.Printf("running goroutines: %d ", ants.Running())
fmt.Printf("finish all tasks. ")
// Use the pool with a method,
// set 10 to the capacity of goroutine pool and 1 second for expired duration.
fn := func(i interface{}) {
myFunc(i)
wg.Done()
}
var mmm []func(i ants.Options)
fno := func(i ants.Options) {
i.PreAlloc = false
i.MaxBlockingTasks = 100
}
mmm = append(mmm, fno)
var hhh ants.Option // 设置携程
lll := &ants.Options{}
lll.PreAlloc = false
lll.MaxBlockingTasks = 100
hhh(lll)
p, _ := ants.NewPoolWithFunc(10, fn, hhh)
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 ", p.Running())
fmt.Printf("finish all tasks, result is %d ", sum)
if sum != 499500 {
panic("the final result is wrong!!!")
}
}

免责声明:文章转载自《go 创建携程池,开启并发》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇seata no available service 'null' found, please make sure registry config correct分享一些免费的,开源的邮件server软件下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Linux 多线程应用中如何编写安全的信号处理函数

http://blog.163.com/he_junwei/blog/static/1979376462014021105242552/ http://www.ibm.com/developerworks/cn/linux/l-cn-signalsec/ Linux 多线程应用中编写安全的信号处理函数 在开发多线程应用时,开发人员一般都会考虑线程安全,会...

经典alsa 录音和播放程序

这里贴上虚拟机ubuntu下alsa的录音程序(capture.c)和播放程序(playback.c)的源码。 首先要测试一下自己的ubuntu是否打开了声音。这个可以打开/系统/首选项/声音  来调节。另外也可以在终端下输入alsaMixer 来调节,之前我的耳机就是只能放音不能录音,因为没有打开一些设置,在进入alsamixer界面后,按F4也就是ca...

c程序的执行过程

1.hello程序的生命周期是从一个高级c语言程序开始的,然后为了在系统上运行hello.c程序,每条c语句都必须被其他程序转化为一系列的低级机器语言指令。 2.预处理阶段。预处理器(cpp)根据以字符#开头的命令,修改原始的C程序。#include <stdio.h>命令告诉预处理器读取系统头文件stdio.h的内容,并将它直接插入到程序文...

time,gettimeofday,clock_gettime

time()提供了秒级的精确度 1、头文件 <time.h> 2、函数原型 time_t time(time_t * timer) 函数返回从UTC1970-1-1 0:0:0开始到现在的秒数 用time()函数结合其他函数(如:localtime、gmtime、asctime、ctime)可以获得当前系统时间或是标准时间。 #inc...

ffmpeg 使用 gdb 调试相关技巧

本文说明了,在ffmpeg二次开发或调用库的过程,如何借助于ffmpeg源码进行调试。 注:ffmpeg版本是4.0。 1. 编写代码 编写将pcm数据转换为mp2的代码 pcm_to_mp2.c #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #i...

Perl脚本学习经验(二)常用命令举例

一.chomp   作      用:去除读入字符串的换行符,去除\n或者\r\n:   简单举例:    while(<FDATA>)    {        my $tmp_record = $_;        chomp ($tmp_record);    }        简单说明:此时$tmp_record变量的结束处已经不包含换行...