Non-blocking I/O in the Go language can be achieved by using pipes: Create an unbuffered pipe: make(chan int) Send data to the pipe: ch <- 1 Receive data from the pipe: val := <-ch Practical case: Creating a non-blocking file reading program
Pipes are an efficient way to communicate in concurrent Go programs. They allow event-based code, where each stage runs independently while data flows asynchronously through the pipeline. This article will show how to use pipes to implement non-blocking I/O in the Go language.
Creating a pipe is very simple:
package main import "fmt" func main() { ch := make(chan int) }
make(chan int)
Create a pipe that can hold int
type of unbuffered pipe. Being unbuffered means that data is transferred from one coroutine to another immediately, which is critical for high-performance I/O applications.
Send data to the pipe:
ch <- 1
Receive data from the pipe:
val := <-ch
Let us create a non-blocking file read Get the program. Assume the file content is:
Hello World
package main import ( "fmt" "bufio" "os" ) func main() { ch := make(chan string) file, err := os.Open("file.txt") if err != nil { fmt.Println(err) return } defer file.Close() go func() { scanner := bufio.NewScanner(file) for scanner.Scan() { ch <- scanner.Text() } ch <- "" // 标记文件读完 }() // 从管道中以非阻塞方式读取行 for { line := <-ch if line == "" { break } fmt.Println(line) } }
This program creates a pipe for transferring file lines. A coroutine is responsible for reading from the file and sending lines to the pipe. The main coroutine then receives the lines from the pipe, and since the pipe is non-blocking, it can continue performing other tasks even if the file reading has not yet completed.
When the file reading is completed, send an empty line to notify the main coroutine to exit the loop.
The above is the detailed content of How to use pipes in Go for non-blocking I/O?. For more information, please follow other related articles on the PHP Chinese website!