natsClient.Subscribe("some_subject", some_callback): Does the 'some_callback' callback run in its own subroutine in Golang?

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

natsClient.Subscribe("some_subject", some_callback): Does the 'some_callback' callback run in its own subroutine in Golang?

问题

基本上,主题说的是。我想知道每次调用回调方法时,nats-lib for golang 是否确保回调在自己的 goroutine 中运行(我有99%的把握,但我需要确认,因为我找不到 nats 中明确说明的文档片段 - 如果我漏掉了什么,请随意复制粘贴任何链接)。

如果回调确实在自己的 goroutine 中运行,我还想知道:

a. 每个特定订阅是否每次都使用相同的 goroutine

或者 b. 每次回调触发时是否创建一个临时的 goroutine:在这种情况下,回调完成后该 goroutine 将被销毁。

英文:

Essentially what the subject says. I'm interested to know whether each time the callback method is invoked the nats-lib for golang ensures that the callback will run on its very own goroutine (I'm 99% sure that it does but I need to make sure because I can't find any explicit piece of documentation in nats that conclusively states it so - feel free to copy paste any links if I've missed something).

If the callback does indeed run in it's own goroutine I'm also interested to know whether:

a. the same goroutine is used every time for a specific subscription

or b. an ephimeral goroutine is created for each firing of the callback: in this case the goroutine gets disposed of after the callback has done its work

答案1

得分: 2

当你调用conn.Subscribe("some_subject", someCallback)时,如果定义了回调函数,它会执行以下代码:

// 如果有异步回调函数,启动一个特定的Go协程来传递消息。
if cb != nil {
    sub.typ = AsyncSubscription
    sub.pCond = sync.NewCond(&sub.mu)
    go nc.waitForMsgs(sub)
}

它为创建的订阅启动了一个Go协程。当消息到达时,它会在waitForMsgs协程中执行定义的回调函数。

简而言之,答案是a. 对于特定的订阅,它每次都使用相同的Go协程。

英文:

When you call conn.Subscribe("some_subject", someCallback), it executes this piece of code if the callback is defined:

// If we have an async callback, start up a sub specific
	// Go routine to deliver the messages.
	if cb != nil {
		sub.typ = AsyncSubscription
		sub.pCond = sync.NewCond(&sub.mu)
		go nc.waitForMsgs(sub)
	}

It launches a goroutine for the created subscription. When a message arrives, it executes the defined callback inside the waitForMsgs goroutine.

In short, the answer is a., it uses the same goroutine every time for a specific subscription.

huangapple
  • 本文由 发表于 2021年11月30日 19:18:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/70168473.html
匿名

发表评论

匿名网友

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

确定