問題:
問題:package main import ( "bufio" "fmt" "os" ) func main() { f, _ := os.Open("D:\input1.txt") scanner := bufio.NewScanner(f) file1chan := make(chan string) for scanner.Scan() { line := scanner.Text() parts := strings.Fields(line) for i := range parts { file1chan <- parts[i] } } print(file1chan) } func print(in <-chan string) { for str := range in { fmt.Printf("%s\n", str) } }
但是,在運行此程式碼時,您會遇到錯誤訊息:「致命錯誤:所有goroutine 都在睡眠- 死鎖!」
解:出現錯誤是因為你的file1chan是一個無緩衝的通道。當您嘗試沿著此通道發送值時,它會無限期地阻塞,等待接收者。要解決此死鎖,您可以啟動一個新的 goroutine 負責將值傳送到通道中,或將通道宣告為緩衝通道。以下概述了兩種方法:
package main import ( "bufio" "fmt" "os" ) func main() { f, _ := os.Open("D:\input1.txt") scanner := bufio.NewScanner(f) file1chan := make(chan string) // Start a new goroutine to send strings down file1chan go func() { for scanner.Scan() { line := scanner.Text() parts := strings.Fields(line) for i := range parts { file1chan <- parts[i] } } close(file1chan) // Close the channel when done sending. }() print(file1chan) // Read strings from file1chan } func print(in <-chan string) { for str := range in { fmt.Printf("%s\n", str) } }
使用新Goroutine:
使用緩衝通道:package main import ( "bufio" "fmt" "os" ) func main() { f, _ := os.Open("D:\input1.txt") scanner := bufio.NewScanner(f) file1chan := make(chan string, 1) // Buffer size of one for scanner.Scan() { line := scanner.Text() parts := strings.Fields(line) for i := range parts { file1chan <- parts[i] } } close(file1chan) // Close the channel when done sending. print(file1chan) } func print(in <-chan string) { for str := range in { // Read all values until channel gets closed fmt.Printf("%s\n", str) } }
以上是Go中使用無緩衝通道時如何解決'致命錯誤:所有 Goroutine 都處於睡眠狀態 - 死鎖!”?的詳細內容。更多資訊請關注PHP中文網其他相關文章!