首頁  >  文章  >  後端開發  >  如何在 Golang 中對 io.PipeRaeder 進行非阻塞 Read()

如何在 Golang 中對 io.PipeRaeder 進行非阻塞 Read()

WBOY
WBOY轉載
2024-02-10 11:10:17389瀏覽

如何在 Golang 中对 io.PipeRaeder 进行非阻塞 Read()

在 Golang 中,io.PipeReader 是常用的讀取器,但它的 Read() 方法在沒有資料可讀時會阻塞程式的執行。那麼如何實現對 io.PipeReader 進行非阻塞的讀取呢? php小編小新為您提供了一種解決方案,透過使用 select 和 goroutine 的方式,我們可以實現對 io.PipeReader 的非阻塞讀取,從而提高程式的回應性和併發性。以下將詳細介紹如何實現此功能,並給出範例程式碼。

問題內容

我有以下程式碼。 5 秒後,可執行程式將向 stdout 發送一些文字。因此,in.readline() 將阻塞直到接收到資料。如何為 readline() 設定逾時或以非阻塞方式執行?

package main

import (
    "bufio"
    "fmt"
    "io"
    "os/exec"
)

func main() {
    cmd := exec.Command("/path/to/executable")

    stdoutReader, stdoutWriter := io.Pipe()

    cmd.Stdout = stdoutWriter

    cmd.Start()

    in := bufio.NewReader(stdoutReader)
    b, _, _ := in.ReadLine()

    fmt.Println(string(b))
}

解決方法

感謝您的評論。我明白了。

package main

import (
    "bufio"
    "fmt"
    "io"
    "os/exec"
    "time"
)

func main() {
    ch := make(chan []byte)
    cmd := exec.Command("/path/to/executable")
    stdoutReader, stdoutWriter := io.Pipe()

    cmd.Stdout = stdoutWriter

    if err := cmd.Start(); err != nil {
        return
    }

    in := bufio.NewReader(stdoutReader)

    go func() {
        b, _, _ := in.ReadLine()
        ch <- b
    }()

    complete := false
    for !complete {
        select {
        case s := <-ch:
            fmt.Println(string(s))
            complete = true
        case <-time.After(time.Second * 5):
            fmt.Println("timeout")
            complete = true
        }
    }

}

以上是如何在 Golang 中對 io.PipeRaeder 進行非阻塞 Read()的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除