- Distributed Computing with Go
- V.N. Nikhil Anurag
- 244字
- 2021-06-24 18:36:11
Concurrent task execution
In the final output of the previous section, we can see that all the tasks in listOfTasks are being executed in serial order, and the last step for maximum concurrency would be to let the order be determined by Go runtime instead of the order in listOfTasks. This might sound like a laborious task, but in reality this is quite simple to achieve. All we need to do is add the go keyword in front of task(&waitGroup):
func main() { var waitGroup sync.WaitGroup // Set number of effective goroutines we want to wait upon waitGroup.Add(len(listOfTasks)) for _, task := range listOfTasks { // Pass reference to WaitGroup instance // Each of the tasks should call on WaitGroup.Done() go task(&waitGroup) // Achieving maximum concurrency } // Wait until all goroutines have completed execution. waitGroup.Wait()
Following is a possible output:
Listened to 10 minutes of audio book. Done listening to audio book. Done booking flight tickets. Done ordering a dress. Done paying Credit Card bills. Wrote 1/3rd of the mail. Wrote 2/3rds of the mail. Done writing the mail. Done making hotel reservation.
If we look at this possible output, the tasks were executed in the following order:
- Listen to audiobook.
- Book flight tickets.
- Order a dress.
- Pay credit card bills.
- Write an email.
- Make hotel reservations.
Now that we have a good idea on what concurrency is and how to write concurrent code using goroutines and WaitGroup, let's dive into parallelism.
推薦閱讀
- Google系統(tǒng)架構(gòu)解密:構(gòu)建安全可靠的系統(tǒng)
- Kali Linux滲透測試全流程詳解
- Haskell Financial Data Modeling and Predictive Analytics
- 高性能Linux服務(wù)器構(gòu)建實戰(zhàn):系統(tǒng)安全、故障排查、自動化運維與集群架構(gòu)
- 計算機系統(tǒng)開發(fā)與優(yōu)化實戰(zhàn)
- Linux就該這么學(xué)
- 嵌入式系統(tǒng)原理及開發(fā)
- Linux使用和管理指南:從云原生到可觀測性
- iOS 8開發(fā)指南
- Vim 8文本處理實戰(zhàn)
- Windows 10從新手到高手
- bash shell腳本編程經(jīng)典實例(第2版)
- Zabbix監(jiān)控系統(tǒng)之深度解析和實踐
- Linux集群之美
- Linux系統(tǒng)安全:縱深防御、安全掃描與入侵檢測