Home  >  Article  >  Backend Development  >  Why does my Go program sometimes print the sum result before the \"display first message\"?

Why does my Go program sometimes print the sum result before the \"display first message\"?

DDD
DDDOriginal
2024-10-30 18:16:03726browse

 Why does my Go program sometimes print the sum result before the

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:

  1. The main function creates two goroutines: display and sum.
  2. The scheduler chooses to switch to the display goroutine first, which prints the "display first message" line.
  3. The display goroutine is blocked when it tries to send data to the channel (c <- true) because there is no receiver yet.
  4. The scheduler chooses to run the sum goroutine, which executes the computationally expensive loop.
  5. Once the sum computation is finished, the sum goroutine sends data to the channel.
  6. The main function receives the data from the channel and exits.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn