"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why is `input.Text()` Evaluated in the Main Goroutine When Using `go` Statements?

Why is `input.Text()` Evaluated in the Main Goroutine When Using `go` Statements?

Published on 2024-11-20
Browse:796

Why is `input.Text()` Evaluated in the Main Goroutine When Using `go` Statements?

Why input.Text() Is Evaluated in the Main Goroutine

In the chapter 8 of The Go Programming Language, the following statement is made about the concurrency echo server:

The arguments to the function started by go are evaluated when the go statement itself is executed; thus input.Text() is evaluated in the main goroutine.

This statement means that when the go statement is executed, the input.Text() function is immediately evaluated, and its result is passed to the go echo() goroutine. This is in contrast to a regular function call, where the function arguments are evaluated when the function is called, and the results are passed to the called function.

The reason for this difference is that go statements start a new goroutine, and goroutines are executed concurrently with the main goroutine. If the arguments to the function started by go were evaluated when the function was called, the main goroutine would have to wait for the function to complete before starting the new goroutine. This would defeat the purpose of using goroutines, which is to enable concurrency.

By evaluating the arguments to the function started by go when the go statement itself is executed, the main goroutine does not have to wait for the function to complete. This allows the goroutines to be started concurrently, which is the desired behavior.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3