Home >Backend Development >Golang >Why does my Go program sometimes print the sum result before the \'display first message\'?
Go Concurrency and Channel Confusion: Understanding Goroutine Execution Order
In Go, concurrency is achieved through goroutines, lightweight threads that run concurrently within a single process. Channels provide a means of communicating between goroutines. However, understanding how goroutines and channels interact can be challenging, especially for beginners.
This article explores a common point of confusion related to goroutine execution order and channel communication. The example program provided:
<code class="go">package main import "fmt" func display(msg string, c chan bool) { fmt.Println("display first message:", msg) c <- true } func sum(c chan bool) { sum := 0 for i := 0; i < 10000000000; i++ { sum++ } fmt.Println(sum) c <- true } func main() { c := make(chan bool) go display("hello", c) go sum(c) <-c }</code>
This program is expected to print "display first message: hello" as the first output, followed by the result of the sum computation. However, in some cases, the sum computation finishes before the display function sends data to the channel.
Explanation:
The scheduler in Go determines the order in which goroutines are executed. It is non-deterministic, meaning the execution order may vary depending on factors such as hardware and operating system. In this example:
However, it is also possible for the scheduler to execute the sum goroutine to completion before the display goroutine sends data to the channel. In this case, the output would be:
10000000000 display first message: hello
Solution:
To ensure that the display message is printed before the sum result, one can use a result channel to receive the first result and exit the program. The modified main function would be:
<code class="go">func main() { result := make(chan string) go display("hello", result) go sum(result) fmt.Println(<-result) }</code>
The above is the detailed content of Why does my Go program sometimes print the sum result before the \'display first message\'?. For more information, please follow other related articles on the PHP Chinese website!