2 回答

TA貢獻(xiàn)1798條經(jīng)驗 獲得超7個贊
這里有一個代碼片段,其中包含一些 worker-goroutine 和一個 processor-goroutine。只有一個 worker-goroutine 可以向處理器發(fā)送一些東西,因為processorChannel它只允許一個條目。處理器完成后,他將響應(yīng)發(fā)回給從中獲得工作的工人。
package main
import (
"fmt"
"time"
)
type WorkPackage struct {
value int
responseChannel chan int
}
func main() {
processorChannel := make(chan *WorkPackage)
for i := 0; i < 3; i++ {
go runWorker(processorChannel)
}
go runProcessor(processorChannel)
// Do some clever waiting here like with wait groups
time.Sleep(5 * time.Second)
}
func runWorker(processorChannel chan *WorkPackage) {
responseChannel := make(chan int)
for i := 0; i < 10; i++ {
processorChannel <- &WorkPackage{
value: i,
responseChannel: responseChannel,
}
fmt.Printf("** Sent %d\n", i)
response := <-responseChannel
fmt.Printf("** Received the response %d\n", response)
// Do some work
time.Sleep(300 * time.Millisecond)
}
}
func runProcessor(processorChannel chan *WorkPackage) {
for workPackage := range processorChannel {
fmt.Printf("## Received %d\n", workPackage.value)
// Do some processing work
time.Sleep(100 * time.Millisecond)
workPackage.responseChannel <- workPackage.value * 100
}
}

TA貢獻(xiàn)1827條經(jīng)驗 獲得超8個贊
我將使用添加兩個數(shù)字的 goroutine 來描述該方法。
聲明 goroutine 的請求和響應(yīng)類型。在請求中包含一個響應(yīng)值通道:
type request struct {
a, b int // add these two numbers
ch chan response
}
type response struct {
n int // the result of adding the numbers
}
啟動接收請求的 goroutine,執(zhí)行操作并將響應(yīng)發(fā)送到請求中的通道:
func startAdder() chan request {
ch := make(chan request)
go func() {
for req := range ch {
req.ch <- response{req.a + req.b}
}
}()
return ch
}
要添加數(shù)字,請使用響應(yīng)通道向 goroutine 發(fā)送請求。在響應(yīng)通道上接收。返回響應(yīng)值。
func add(ch chan request, a, b int) int {
req := request{ch: make(chan response), a: a, b: b}
ch <- req
return (<-req.ch).n
}
像這樣使用它:
ch := startAdder()
fmt.Println(add(ch, 1, 2))
在 GoLang PlayGround 上運(yùn)行它。
- 2 回答
- 0 關(guān)注
- 123 瀏覽
添加回答
舉報