为了账号安全,请及时绑定邮箱和手机立即绑定

sync.Waitgroup 不被尊重

sync.Waitgroup 不被尊重

Go
绝地无双 2022-10-10 19:50:25
我注意到许多 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 hoursfunc 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 ”输出行。
查看完整描述

1 回答

?
缥缈止盈

TA贡献2041条经验 获得超4个赞

每次启动 goroutine 后,原始代码会阻塞,等待通过非缓冲通道发送一个值,此外,当WaitGroup倒计时时通道关闭,这也关闭了接收端的通道。

恕我直言,一般规则是:

不要从接收方关闭通道,如果通道有多个并发发送方,也不要关闭通道。

package main


import (

    "fmt"

    "strings"

)


type StratNotification struct {

    Symbol string

}


func GetSymbols() []StratNotification {

    return []StratNotification{

        {Symbol: "a"},

        {Symbol: "b"},

        {Symbol: "c"},

        {Symbol: "d"},

    }

}


func RunIntradayScanner() {

    symbols := GetSymbols()

    var intradayChannel = make(chan StratNotification)

    for _, s := range symbols {

        go IntradayStratify(strings.TrimSpace(s.Symbol), intradayChannel)

    }


    for _ = range symbols {

        s := <-intradayChannel

        fmt.Println(s)

    }

}


func IntradayStratify(ticker string, c chan StratNotification) {

    // do some heavy lifting

    fmt.Println(ticker)

    c <- StratNotification{}

}


func main() {

    RunIntradayScanner()

}


查看完整回答
反对 回复 2022-10-10
  • 1 回答
  • 0 关注
  • 115 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号