登录
首页 >  Golang >  Go问答

Goroutines - 向单个goroutine发送关键数据并等待结果的处理

来源:stackoverflow

时间:2024-02-08 18:51:21 106浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《Goroutines - 向单个goroutine发送关键数据并等待结果的处理》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

我的应用程序中运行着许多 goroutine,并且我还有另一个 goroutine,它必须在同一时间段仅处理一个请求,然后将结果发送回调用者。

这意味着其他 goroutine 应该等待,直到必要的(单操作的)goroutine 繁忙。

[goroutine 1] <-
                 -
                   -
                     -
[goroutine 2]<- - - -  -> [Process some data in a single goroutine and send the result back to caller
                     -
                   -
                 -
[goroutine 3] <-

这是图表的样子

我对 go 非常陌生,我对如何正确实现它知之甚少。

有人可以为我提供一些工作示例,以便我可以在演示中运行它吗?


正确答案


这里是一个代码片段,其中有一些工作协程和一个处理器协程。只有一个工作协程可以向处理器发送一些内容,因为 processorchannel 只允许一个条目。当处理器完成后,他将响应发送回他从中获取工作的工作人员。

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
    }
}

我将使用一个将两个数字相加的 goroutine 来描述该方法。

声明 goroutine 的请求和响应类型。在请求中包含响应值通道:

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,接收请求,执行操作并将响应发送到请求中的通道:

func startadder() chan request {
    ch := make(chan request)
    go func() {
        for req := range ch {
            req.ch <- response{req.a + req.b}
        }
    }()
    return ch
}

要添加数字,请使用响应通道向 goroutine 发送请求。在响应通道上接收。返回响应值。

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))

Run it on the GoLang PlayGround

今天关于《Goroutines - 向单个goroutine发送关键数据并等待结果的处理》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>