Home  >  Article  >  Backend Development  >  Why is `input.Text()` evaluated in the main goroutine when creating a new goroutine with `go`?

Why is `input.Text()` evaluated in the main goroutine when creating a new goroutine with `go`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-16 13:18:03832browse

Why is `input.Text()` evaluated in the main goroutine when creating a new goroutine with `go`?

Why input.Text() is evaluated in the main goroutine

When creating a new goroutine with the go keyword, the function's parameters and arguments are evaluated at the time the go statement is executed, not when the goroutine actually starts running. This means that any variables or expressions used as parameters or arguments will be evaluated in the main goroutine.

In the example provided, the function handleConn is called as a goroutine with the go keyword. The function takes a single argument, c, which references a net.Conn object representing a network connection. Inside the handleConn function, a bufio.Scanner is created using the c connection, and the Scan method is repeatedly called on the scanner to read input from the connection.

Within the loop, the Scan method is called on the input scanner, and the line of text read from the connection is accessed using the Text method. The input.Text() expression is evaluated within the main goroutine, and the text is returned to the handleConn goroutine as the result of the Scan method.

In this particular example, the handleConn goroutine repeatedly calls go echo(c, input.Text(), 1*time.Second) to create a new goroutine that echoes the input text back to the client. Because input.Text() is evaluated in the main goroutine, the values for input.Text() and 1*time.Second are determined at the time the go statement is executed, not when the echo goroutine begins running.

The above is the detailed content of Why is `input.Text()` evaluated in the main goroutine when creating a new goroutine with `go`?. 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