【发布时间】:2016-05-30 05:37:28
【问题描述】:
我需要一些帮助来理解如何在这个问题中使用 goroutine。我将只发布一些 sn-ps 代码,但如果您想深入了解,可以查看 here
基本上,我有一个分发器函数,它接收被多次调用的请求切片,每次调用该函数时,它必须在其他函数中分发该请求以实际解决请求。以及我正在尝试创建一个通道并启动此功能以解决新 goroutine 上的请求,因此程序可以同时处理请求。
distribute 函数是如何调用的:
// Run trigger the system to start receiving requests
func Run() {
// Since the programs starts here, let's make a channel to receive requests
requestCh := make(chan []string)
idCh := make(chan string)
// If you want to play with us you need to register your Sender here
go publisher.Sender(requestCh)
go makeID(idCh)
// Our request pool
for request := range requestCh {
// add ID
request = append(request, <-idCh)
// distribute
distributor(request)
}
// PROBLEM
for result := range resultCh {
fmt.Println(result)
}
}
分发函数本身:
// Distribute requests to respective channels.
// No waiting in line. Everybody gets its own goroutine!
func distributor(request []string) {
switch request[0] {
case "sum":
arithCh := make(chan []string)
go arithmetic.Exec(arithCh, resultCh)
arithCh <- request
case "sub":
arithCh := make(chan []string)
go arithmetic.Exec(arithCh, resultCh)
arithCh <- request
case "mult":
arithCh := make(chan []string)
go arithmetic.Exec(arithCh, resultCh)
arithCh <- request
case "div":
arithCh := make(chan []string)
go arithmetic.Exec(arithCh, resultCh)
arithCh <- request
case "fibonacci":
fibCh := make(chan []string)
go fibonacci.Exec(fibCh, resultCh)
fibCh <- request
case "reverse":
revCh := make(chan []string)
go reverse.Exec(revCh, resultCh)
revCh <- request
case "encode":
encCh := make(chan []string)
go encode.Exec(encCh, resultCh)
encCh <- request
}
}
还有 fibonacci.Exec 函数来说明我如何尝试计算斐波那契给定在 fibCh 上收到的请求并通过 resultCh 发送结果值。
func Exec(fibCh chan []string, result chan map[string]string) {
fib := parse(<-fibCh)
nthFibonacci(fib)
result <- fib
}
到目前为止,在 Run 函数中,当我覆盖 resultCh 时,我得到了结果,但也出现了死锁。但为什么?另外,我想我应该使用 waitGroup 函数来等待 goroutines 完成,但我不确定如何实现它,因为我期待收到连续的请求流。对于理解我在这里做错了什么以及解决它的方法,我将不胜感激。
【问题讨论】: