Golang's understanding of reading data from the pipe after closing the pipe

misunderstanding

There are two ways to write the receive operation, one with "ok", which reflects whether the channel is closed; one without "ok"

The above statement comes from the "What is the process of receiving data from a channel" chapter of " Go Programmer Interview Written Test Guide ".

Actually this is not accurate. The second variable that returns the writing method of the two variables does not directly represent whether the channel is closed. Take the following code as an example:

func main() {
    
    
	ch := make(chan int, 5)
	ch <- 18
	close(ch)
	x, ok := <-ch
	if ok {
    
    
		fmt.Println("received: ", x)
	}

	x, ok = <-ch
	if !ok {
    
    
		fmt.Println("channel closed, data invalid.")
	}
}

operation result:

received:  18
channel closed, data invalid.

First create a buffered channel, send an element to it, and then close the channel. After two attempts to read data from the channel, the first time the value can still be read normally, and the returned ok is true, but the channel has been closed. The ok returned for the second time is false, indicating that the channel has been closed and there is no data in the channel.

Correct understanding

The correct understanding of continuing to read and write after the channel is closed is as follows:

Pipes can be closed using built-in functions close(). Trying to write data to a closed pipe will trigger a panic, but the closed pipe is still readable.

Pipe reading expressions can assign values ​​to up to two variables:

v1 := <-ch
x, ok := <-ch

The first variable represents the data alone, and the second variable (bool type) represents whether the data has been read successfully. It should be noted that the second variable is not used to indicate the closing status of the pipe.

The second variable is often misunderstood as the closed status of the pipe. That is because its value is indeed related to the closed status of the pipe, or more precisely to whether there is data in the pipe buffer.

There are two situations for a closed pipeline:

  • There is no data in the pipe buffer;
  • The pipe buffer still has data.

For the first case, the pipe has been closed and there is no data in the buffer, then the first variable returned by the pipe read expression is a zero value of the response type, and the second variable is false.

For the second case, the pipe has been closed but there is still data in the buffer, then the first variable returned by the pipe reading expression is the read data, and the second variable is true. It can be seen that only when the pipe is closed and there is no data in the buffer, the second variable returned by the pipe read expression is consistent with the pipe closing status.

Guess you like

Origin blog.csdn.net/qq_26356861/article/details/131668049