您好,登錄后才能下訂單哦!
這期內(nèi)容當中小編將會給大家?guī)碛嘘P(guān)golang中怎么實現(xiàn)并發(fā)數(shù)控制,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
golang并發(fā)
談到golang這門語言,很自然的想起了他的的并發(fā)goroutine。這也是這門語言引以為豪的功能點。并發(fā)處理,在某種程度上,可以提高我們對機器的使用率,提升系統(tǒng)業(yè)務(wù)處理能力。但是并不是并發(fā)量越大越好,太大了,硬件環(huán)境就會吃不消,反而會影響到系統(tǒng)整體性能,甚至奔潰。所以,在使用golang提供便捷的goroutine時,既要能夠?qū)崿F(xiàn)開啟并發(fā),也要學會如果控制并發(fā)量。
開啟golang并發(fā)
golang開啟并發(fā)處理非常簡單,只需要在調(diào)用函數(shù)時,在函數(shù)前邊添加上go關(guān)鍵字即可。如下邊例子所示:
package main import ( "fmt" "time" ) type Demo struct { input chan string output chan string max_goroutine chan int } func NewDemo() *Demo { d := new(Demo) d.input = make(chan string, 24) d.output = make(chan string, 24) d.max_goroutine = make(chan int, 20) return d } func (this *Demo) Goroutine() { var i = 1000 for { this.input <- time.Now().Format("2006-01-02 15:04:05") time.Sleep(time.Second * 1) if i < 0 { break } i-- } close(this.input) } func (this *Demo) Handle() { for t := range this.input { fmt.Println("datatime is :", t) this.output <- t } } func main() { demo := NewDemo() go demo.Goroutine() demo.Handle() }
上邊代碼,在調(diào)用Demo的Goroutine方法時,在前邊加上了go關(guān)鍵字,則函數(shù)Goroutine并發(fā)執(zhí)行開啟成功。
可見,在golang中開啟并發(fā)非常的方便。
下邊再來看看,在golang中,怎么實現(xiàn)并發(fā)量的控制。
當goroutine并發(fā)執(zhí)行的任務(wù)達到一定值時,主程序等待goroutine執(zhí)行完成退出,一旦發(fā)現(xiàn)并發(fā)數(shù)量低于某一個設(shè)定的值,就從新開始執(zhí)行主程序邏輯。
實現(xiàn)代碼如下:
package main import ( "fmt" "time" ) type Demo struct { input chan string output chan string goroutine_cnt chan int } func NewDemo() *Demo { d := new(Demo) d.input = make(chan string, 8192) d.output = make(chan string, 8192) d.goroutine_cnt = make(chan int, 10) return d } func (this *Demo) Goroutine() { this.input <- time.Now().Format("2006-01-02 15:04:05") time.Sleep(time.Millisecond * 500) <-this.goroutine_cnt } func (this *Demo) Handle() { for t := range this.input { fmt.Println("datatime is :", t, "goroutine count is :", len(this.goroutine_cnt)) this.output <- t + "handle" } } func main() { demo := NewDemo() go demo.Handle() for i := 0; i < 10000; i++ { demo.goroutine_cnt <- 1 go demo.Goroutine() } close(demo.input) }
如上邊示例,Goroutine()函數(shù),每隔500毫秒寫入一個時間戳到管道中,不考慮管道的讀取時間,也就是說,每個Goroutine會存在大概500毫秒時間,如果不做控制的話,一瞬間可以開啟上萬個甚至更多的goroutine出來,這樣系統(tǒng)就會奔潰。
在上述代碼中,我們引入了帶10個buffer的chan int字段,每創(chuàng)建一個goroutine時,就會向這個chan中寫入一個1,每完成一個goroutine時,就會從chan中彈出一個1。當chan中裝滿10個1時,就會自動阻塞,等待goroutine執(zhí)行完,彈出chan中的值時,才能繼續(xù)開啟goroutine。通過chan阻塞特點,實現(xiàn)了goroutine的最大并發(fā)量控制。
上述就是小編為大家分享的golang中怎么實現(xiàn)并發(fā)數(shù)控制了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。