我正在嘗試實施一個字數統計程序,但第一步我遇到了一些問題。Golang goroutine不會與頻道內部運行
這裏是我的代碼:
package main
import (
"fmt"
"os"
"bufio"
"sync"
)
// Load data into channel
func laodData(arr []string,channel chan string,wg sync.WaitGroup) {
for _,path := range arr {
file,err := os.Open(path)
fmt.Println("begin to laodData ", path)
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
defer file.Close()
reader := bufio.NewReaderSize(file, 32*10*1024)
i := 0
for {
line,err := reader.ReadString('\n')
channel <- line
if err != nil {
break
}
i++
if i%200 == 0 {
fmt.Println(i," lines parsed")
}
}
fmt.Println("finish laodData ", path)
}
wg.Done()
}
// dispatch data lines into different mappers
func dispatcher(channel chan string,wg sync.WaitGroup){
fmt.Println("pull data 11")
line,ok := <- channel
fmt.Println(ok)
for ok {
fmt.Println(line)
line,ok = <- channel
}
fmt.Println("pull data 22")
wg.Done()
}
func main() {
path := os.Args
if len(path) < 2 {
fmt.Println("Need Input Files")
os.Exit(0)
}
var wg sync.WaitGroup
wg.Add(2)
channel := make(chan string)
defer close(channel)
fmt.Println("before dispatcher")
go laodData(path[1:],channel,wg)
go dispatcher(channel,wg)
wg.Wait()
fmt.Println("after dispatcher")
}
這是我的輸出:
...
finish laodData result.txt
throw: all goroutines are asleep - deadlock!
goroutine 1 [semacquire]:
sync.runtime_Semacquire(0x42154100, 0x42154100)
/usr/local/go/src/pkg/runtime/zsema_amd64.c:146 +0x25
sync.(*WaitGroup).Wait(0x4213b440, 0x0)
/usr/local/go/src/pkg/sync/waitgroup.go:79 +0xf2
main.main()
/Users/kuankuan/go/src/mreasy/main.go:66 +0x238
goroutine 2 [syscall]:
created by runtime.main
/usr/local/go/src/pkg/runtime/proc.c:221
goroutine 4 [chan receive]:
main.dispatcher(0x42115a50, 0x0, 0x2, 0x0)
/Users/kuankuan/go/src/mreasy/main.go:45 +0x223
created by main.main
/Users/kuankuan/go/src/mreasy/main.go:65 +0x228
exit status 2
謝謝!
在這種精確的情況下,去掉'go dispatcher(path [1:],channel)'中的'go'會更簡單。 –
謝謝@dystory,我需要在主線程旁邊的調度員旁邊做其他事情。 – MrROY
嗨,勝利者,我遵循你的建議,但我遇到了死鎖!問題。**拋出:所有的goroutines都睡着了 - 僵局! channel < - line ** – MrROY