英文:
go routine, function executed out of desired order
问题
嗨,我正在学习goroutine,并且我有一个问题。我有一段代码,其中包含一个发布者和一个监听器,我需要先执行订阅调用,然后再执行发布调用。
useCase := New(tt.fields.storage)
tt.fields.wg.Add(1)
go func() {
ch, _, err := useCase.Subscribe(tt.args.ctx, tt.args.message.TopicName)
message, ok := <-ch
if !ok {
close(ch)
tt.fields.wg.Done()
}
require.NoError(t, err)
assert.Equal(t, tt.want, message)
}()
err := useCase.Publish(tt.args.ctx, tt.args.message)
tt.fields.wg.Wait()
由于我在这两个函数中发送消息,我需要使用goroutine。请问如何确保订阅始终先执行,然后再执行发布操作?
英文:
Hi I'm learning goroutine, and I have a question I have a code where I have a publisher and a listener, I need the subscribe call to happen first then the publish call.
useCase := New(tt.fields.storage)
tt.fields.wg.Add(1)
go func() {
ch, _, err := useCase.Subscribe(tt.args.ctx, tt.args.message.TopicName)
message, ok := <- ch
if !ok {
close(ch)
tt.fields.wg.Done()
}
require.NoError(t, err)
assert.Equal(t, tt.want, message)
}()
err := useCase.Publish(tt.args.ctx, tt.args.message)
tt.fields.wg.Wait()
and as I send messages inside these two functions I need Go Func, how would I get subscribe to always execute first, and then publish.
答案1
得分: 3
你可以使用一个通道:
subscribed := make(chan struct{})
go func() {
ch, _, err := useCase.Subscribe(tt.args.ctx, tt.args.message.TopicName)
if err != nil {
...
}
close(subscribed)
message, ok := <-ch
...
}()
<-subscribed
err := useCase.Publish(tt.args.ctx, tt.args.message)
英文:
You can use a channel:
subscribed:=make(chan struct{})
go func() {
ch, _, err := useCase.Subscribe(tt.args.ctx, tt.args.message.TopicName)
if err!=nil {
...
}
close(subscribed)
message, ok := <- ch
...
}()
<-subscribed
err := useCase.Publish(tt.args.ctx, tt.args.message)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论