官术网_书友最值得收藏!

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:

  1. Listen to audiobook.
  2. Book flight tickets.
  3. Order a dress.
  4. Pay credit card bills.
  5. Write an email.
  6. 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.

主站蜘蛛池模板: 突泉县| 白水县| 普兰县| 博湖县| 华阴市| 随州市| 偃师市| 永新县| 安阳市| 甘谷县| 河南省| 万荣县| 湘乡市| 南开区| 阳江市| 新乐市| 洪雅县| 兴安盟| 正阳县| 凤山市| 海盐县| 什邡市| 固镇县| 夏河县| 大洼县| 都昌县| 乐昌市| 蒙城县| 海南省| 堆龙德庆县| 绥阳县| 华阴市| 阳江市| 鲁山县| 绥滨县| 嵊州市| 云和县| 平湖市| 平阳县| 昂仁县| 弥勒县|