Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asynchronous Golang持久通道接受来自多个函数调用的输入_Asynchronous_Go_Synchronization_Channel - Fatal编程技术网

Asynchronous Golang持久通道接受来自多个函数调用的输入

Asynchronous Golang持久通道接受来自多个函数调用的输入,asynchronous,go,synchronization,channel,Asynchronous,Go,Synchronization,Channel,我有一个函数a: func a(input *some_type) { // do sth. b(input) } 此函数被多次调用。 我希望函数b无限期地等待函数a的输入,并在收集了n个输入后执行操作 func b(input *some_type) { // wait until received n inputs then do sth. with all inputs } 我该怎么做呢?我的第一个想法是使用一个sync.WaitGroup,在a

我有一个函数
a

func a(input *some_type) {
    // do sth.
    b(input)
    }
此函数被多次调用。 我希望函数
b
无限期地等待函数
a
的输入,并在收集了n个输入后执行操作

func b(input *some_type) {
    // wait until received n inputs then do sth. with all inputs
    }

我该怎么做呢?我的第一个想法是使用一个
sync.WaitGroup
,在
a
b
之间有一个频道,这是一个常见的生产者-消费者问题。使用通道等待来自另一个例程的输入。像这样的东西有用吗

在这个特定的示例中,在收集完输入后,您必须再次调用
go b(c)
,但您可以轻松地将
b
所做的任何事情包装在无限
for
循环中。或者任何需要发生的事情

请注意,在本例中,使用了无缓冲的
通道
,这迫使两个例程同时相遇,以“传递”
*事物
。如果希望生产者(
a
的进程)不必等待,可以使用缓冲通道,其创建方式如下:

c := make(chan(*Thing, n))
其中
n
是频道可以存储的项目数。这允许多个生产者排队

主程序包
进口(
“fmt”
“时间”
)
类型事物结构{
N int
}
func a(t*Thing,c chan(*Thing)){
//事情就这样发生了
C
package main

import (
    "fmt"
    "time"
)

type Thing struct {
    N int
}

func a(t *Thing, c chan (*Thing)) {
    // stuff happens. whee
    c <- t
}

func b(c chan (*Thing)) {
    things := []*Thing{}
    for i := 0; i < 10; i++ {
        t := <-c
        things = append(things, t)
        fmt.Printf("I have %d things\n", i+1)
    }
    fmt.Println("I now have 10 things! Let's roll!")
    // do stuff with your ten things
}

func main() {
    fmt.Println("Hello, playground")
    c := make(chan (*Thing))

    go b(c)

    // this would probably be done producer-consumer like in a go-routine
    for i := 0; i < 10; i++ {
        a(&Thing{i}, c)
        time.Sleep(time.Second)
    }
    time.Sleep(time.Second)
    fmt.Println("Program finished")
}