golang併發數量及超時控制

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。 這裡介紹一個控制golang併發數量的包gowork,當然都是可以自己實現的,只是每次去實現比較麻煩罷了。 如果只是啟一個goroutine那就沒有必要使用,當然這個包也是支援的。 實現原理:用戶告知要啟用的併發數量,然後包內會啟動相當於併發數量的一個工作池。這樣之後程式猿只要往工作池裡面發任務就可以了。 當然你需要的是實現你的worker。原型:type WorkFunction func(req interface{}, res interface{})還可以實現異常處理的函數,原型和worker一樣,同時在使用的時候gowork會自動將任務參數req對應的傳給異常處理函數,你需要做的是通過req獲取異常處理結果,當然你也可以不要這些結果。 使用:控制同時併發數量為5,new一個WorkManager來管理goroutine,通過 NewGoroutine啟動worker池,然後就可以AddRequest發布任務去執行了。  
package mainimport (    "fmt"    "github.com/qianlnk/gowork")type People struct {    Id   int    Name string}func SayHello(request, response interface{}) {    req := request.(People)    fmt.Printf("Hello, I'm %s, My ID is %d.\n", req.Name, req.Id)}func SingSong(request, response interface{}) {    req := request.(People)    fmt.Printf("My ID is %d, what I will sing is test_%s\n", req.Id, req.Name)}func main() {    wm := gowork.NewWorkManager()    wm.NewGoroutine("sayhello", 5, SayHello, nil)    wm.NewGoroutine("singsong", 5, SingSong, nil)    go func() {        for i := 1; i < 20; i++ {            pl := People{                Id:   i,                Name: fmt.Sprintf("hello%d", i),            }            wm.AddRequest("sayhello", pl)        }        wm.Done("sayhello")    }()    for i := 0; i < 20; i++ {        pl := People{            Id:   i,            Name: fmt.Sprintf("song%d", i),        }        wm.AddRequest("singsong", pl)    }    wm.Done("singsong")}
當然 ,如果你願意你也可以把發布任務也起成goroutine這樣調用Done的時候程式會等待任務發佈完成並全部執行結束。 具體使用可以移駕github:https://github.com/qianlnk/gowork  
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.