sync.Waitgroup 不被尊重

我注意到许多 goroutines 仍在运行,即使程序应该等待它们全部完成。我的理解是添加一个等待组可以解决这个问题,但它没有。

if len(tf5) > 0 {

        SplitUpAndSendEmbedToDiscord(5, tf5)

    }


    if len(tf15) > 0 {

        SplitUpAndSendEmbedToDiscord(15, tf15)

    }


    if len(tf30) > 0 {

        SplitUpAndSendEmbedToDiscord(30, tf30)

    }


    if len(tf60) > 0 {

        SplitUpAndSendEmbedToDiscord(60, tf60)

    }

}


// IntradayStratify - go routine to run during market hours

func IntradayStratify(ticker string, c chan request.StratNotification, wg *sync.WaitGroup) {

    defer wg.Done()


    candles := request.GetIntraday(ticker)

    for _, tf := range timeframes {

        chunkedCandles := request.DetermineTimeframes(tf, ticker, candles)

        if len(chunkedCandles) > 1 {

            highLows := request.CalculateIntraDayHighLow(chunkedCandles)

            // logrus.Infof("%s Highlows calculated: %d", ticker, len(highLows))

            // Should have more than 2 candles to start detecting patterns now

            if len(highLows) > 2 {

                bl, stratPattern := request.DetermineStratPattern(ticker, tf, highLows)

                if bl {

                    c <- stratPattern

                }

            }

        }


        // otherwise return an empty channel

        c <- request.StratNotification{}

    }


}


func main() {

  RunIntradayScanner()

}

for我期望程序在循环遍历符号后再次变成单线程。相反,stdout 如下所示,看起来 goroutines 仍在返回。结果应该是每行写着“ Pattern XX found for timeframe ”也将有一个相应的“ Sending to discord ”输出行。


绝地无双
浏览 116回答 1
1回答

缥缈止盈

每次启动 goroutine 后,原始代码会阻塞,等待通过非缓冲通道发送一个值,此外,当WaitGroup倒计时时通道关闭,这也关闭了接收端的通道。恕我直言,一般规则是:不要从接收方关闭通道,如果通道有多个并发发送方,也不要关闭通道。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strings")type StratNotification struct {&nbsp; &nbsp; Symbol string}func GetSymbols() []StratNotification {&nbsp; &nbsp; return []StratNotification{&nbsp; &nbsp; &nbsp; &nbsp; {Symbol: "a"},&nbsp; &nbsp; &nbsp; &nbsp; {Symbol: "b"},&nbsp; &nbsp; &nbsp; &nbsp; {Symbol: "c"},&nbsp; &nbsp; &nbsp; &nbsp; {Symbol: "d"},&nbsp; &nbsp; }}func RunIntradayScanner() {&nbsp; &nbsp; symbols := GetSymbols()&nbsp; &nbsp; var intradayChannel = make(chan StratNotification)&nbsp; &nbsp; for _, s := range symbols {&nbsp; &nbsp; &nbsp; &nbsp; go IntradayStratify(strings.TrimSpace(s.Symbol), intradayChannel)&nbsp; &nbsp; }&nbsp; &nbsp; for _ = range symbols {&nbsp; &nbsp; &nbsp; &nbsp; s := <-intradayChannel&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(s)&nbsp; &nbsp; }}func IntradayStratify(ticker string, c chan StratNotification) {&nbsp; &nbsp; // do some heavy lifting&nbsp; &nbsp; fmt.Println(ticker)&nbsp; &nbsp; c <- StratNotification{}}func main() {&nbsp; &nbsp; RunIntradayScanner()}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go