- 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.
推薦閱讀
- Mastering ElasticSearch
- Red Hat Enterprise Linux 8系統管理實戰
- Linux網絡操作系統與實訓(第三版)
- vSphere Virtual Machine Management
- 精通Linux內核開發
- 嵌入式Linux驅動程序和系統開發實例精講
- 嵌入式操作系統(Linux篇)(微課版)
- 突破平面3ds Max動畫設計與制作
- 跟老男孩學Linux運維:Shell編程實戰
- Kali Linux高級滲透測試(原書第3版)
- Heroku Cloud Application Development
- 大學計算機應用基礎實踐教程(Windows 7+MS Office 2010)
- Learn OpenShift
- Implementing Domain-Specific Languages with Xtext and Xtend(Second Edition)
- 計算機應用基礎(Windows 7+Office 2010)