协程,函数执行顺序不符合预期。

huangapple go评论92阅读模式
英文:

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 :=  &lt;- 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 :=  &lt;- ch
   ...
}()
&lt;-subscribed
err := useCase.Publish(tt.args.ctx, tt.args.message)


</details>



huangapple
  • 本文由 发表于 2021年9月30日 04:36:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/69383069.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定