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

Parallelism

Imagine that you have to write a few emails. They are going to be long and laborious, and the best way to keep yourself entertained is to listen to music while writing them, that is, listening to music "in parallel" to writing the emails. If we wanted to write a program that simulates this scenario, the following is one possible implementation:

package main 
 
import ( 
    "fmt" 
    "sync" 
    "time" 
) 
 
func printTime(msg string) { 
    fmt.Println(msg, time.Now().Format("15:04:05")) 
} 
 
// Task that will be done over time 
func writeMail1(wg *sync.WaitGroup) { 
    printTime("Done writing mail #1.") 
    wg.Done() 
} 
func writeMail2(wg *sync.WaitGroup) { 
    printTime("Done writing mail #2.") 
    wg.Done() 
} 
func writeMail3(wg *sync.WaitGroup) { 
    printTime("Done writing mail #3.") 
    wg.Done() 
} 
 
// Task done in parallel 
func listenForever() { 
    for { 
        printTime("Listening...") 
    } 
} 
 
func main() { 
    var waitGroup sync.WaitGroup 
    waitGroup.Add(3) 
 
    go listenForever() 
 
    // Give some time for listenForever to start 
    time.Sleep(time.Nanosecond * 10) 
 
    // Let's start writing the mails 
    go writeMail1(&waitGroup) 
    go writeMail2(&waitGroup) 
    go writeMail3(&waitGroup) 
 
    waitGroup.Wait() 
} 

The output of the program might be as follows:

Done writing mail #3. 19:32:57
Listening... 19:32:57
Listening... 19:32:57
Done writing mail #1. 19:32:57
Listening... 19:32:57
Listening... 19:32:57
Done writing mail #2. 19:32:57

The numbers represent the time in terms of Hour:Minutes:Seconds and, as can be seen, they are being executed in parallel. You might have noticed that the code for parallelism looks almost identical to the code for the final concurrency example. However, in the function listenForever, we are printing Listening... in an infinite loop. If the preceding example was written without goroutines, the output would keep printing Listening... and never reach the writeMail function calls.

Now that we understand how goroutine can be used to run concurrent programs, let's look at how Go is allowing us to do this. We shall next look at the scheduler used by Go runtime.

主站蜘蛛池模板: 尼木县| 武胜县| 利津县| 乳山市| 油尖旺区| 阿拉善盟| 延津县| 盈江县| 霍林郭勒市| 沙雅县| 准格尔旗| 四平市| 西丰县| 桦南县| 嘉荫县| 英超| 秦安县| 万山特区| 伊吾县| 云和县| 调兵山市| 汉源县| 鹰潭市| 安远县| 湟源县| 民县| 沂南县| 宁阳县| 开封县| 临猗县| 连城县| 昭通市| 施甸县| 南郑县| 昔阳县| 九江县| 闻喜县| 黄大仙区| 翁牛特旗| 吉木萨尔县| 石阡县|