package mainimport ( "fmt" "sync" "time")// 方法一: 通过sync.WaitGroup + chan自定义var tokens chan struct{}var wg sync.WaitGroupfunc fprint(num int) { defer wg.Done() time.Sleep(10 * time.Microsecond) <-tokens fmt.Println(num)}func main() { t1 := time.Now() tokens = make(chan struct{}, 500) // 并发数量 for num := 0; num < 100000; num++ { fmt.Printf("插入一个%d\n", num) wg.Add(1) tokens <- struct{}{} // fmt.Printf("队列长度----%d\n", len(tokens)) go fprint(num) } wg.Wait() t := time.Since(t1) fmt.Println(t)}
package mainimport ( "fmt" "sync" "time" "github.com/panjf2000/ants/v2")func myFunc(num int32) { time.Sleep(10 * time.Microsecond) fmt.Println(num)}func demoFunc(num int32) { time.Sleep(10 * time.Microsecond) fmt.Println(num)}func main() { t1 := time.Now() defer ants.Release() runTimes := 100000 var wg sync.WaitGroup //方法二:使用ants默认数量的goroutinues,打开源码可以看到链接池的容量大小为: math.MaxInt32*(2147483647) // Use the common pool. syncCalculateSum := func(num int32) func() { return func() { demoFunc(num) fmt.Printf("running goroutines: %d\n", ants.Running()) wg.Done() } } for i := 0; i < runTimes; i++ { wg.Add(1) _ = ants.submit(syncCalculateSum(int32(i))) //ants.submit只接收func类型的参数 } wg.Wait() // fmt.Printf("running goroutines: %d\n", ants.Running()) fmt.Printf("finish all tasks.\n") //方法三:使用自定义数量的goroutinues // Use the pool with a function, // set 475 to the capacity of goroutine pool and 1 second for expired duration. p, _ := ants.NewPoolWithFunc(475, func(i interface{}) { // 并发数量475 myFunc(i.(int32)) //业务函数 wg.Done() }, ants.WithPreAlloc(true)) defer p.Release() // submit tasks one by one. for i := 0; i < runTimes; i++ { wg.Add(1) fmt.Printf("running goroutines: %d\n", p.Running()) _ = p.Invoke(int32(i)) // 传递业务函数的参数 } wg.Wait() fmt.Printf("finish all tasks\n") t := time.Since(t1) fmt.Println(t)}
总结
以上是内存溢出为你收集整理的实现go并发的三种方式全部内容,希望文章能够帮你解决实现go并发的三种方式所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)