zoukankan      html  css  js  c++  java
  • gorouting使用

    1.起固定個數的goroutine

    package utils
    
    import (
    	"sync"
    )
    
    type pool struct {
    	queue chan int
    	wg    *sync.WaitGroup
    }
    
    func New(size int) *pool {
    	if size <= 0 {
    		size = 1
    	}
    	return &pool{
    		queue: make(chan int, size),
    		wg:    &sync.WaitGroup{},
    	}
    }
    
    func (p *pool) Add(delta int) {
    	for i := 0; i < delta; i++ {
    		p.queue <- 1
    	}
    	for i := 0; i > delta; i-- {
    		<-p.queue
    	}
    	p.wg.Add(delta)
    }
    
    func (p *pool) Done() {
    	<-p.queue
    	p.wg.Done()
    }
    
    func (p *pool) Wait() {
    	p.wg.Wait()
    }
    

    ** // 使用示例**

    // 初始化数据,创建10个goroutine
    pool := utils.New(10)
    
    for i:=0; i< 100;i++ {
        pool.Add(1)
        go func() {
            DOSomething()
            pool.Done()
        }
    }
    
    pool.Wait()
    

    2.重试机制

    func Retry(attempts int, sleep time.Duration, f func() error) (err error) {
        for i := 0; ; i++ {
            err = f()
            if err == nil {
                return
            }
    
            if i >= (attempts - 1) {
                break
            }
    
            time.Sleep(sleep)
    
        }
        return fmt.Errorf("after %d attempts, last error: %v", attempts, err)
    }
    
    【励志篇】: 古之成大事掌大学问者,不惟有超世之才,亦必有坚韧不拔之志。
  • 相关阅读:
    信息收集-DNS
    Xshell下载
    JSP
    本地网络配置
    P1485 火枪打怪
    P4155 [SCOI2015]国旗计划
    P1017 [NOIP2000 提高组] 进制转换
    P1013 [NOIP1998 提高组] 进制位
    P1011 [NOIP1998 提高组] 车站
    CF841B Godsend
  • 原文地址:https://www.cnblogs.com/tomtellyou/p/13867645.html
Copyright © 2011-2022 走看看