运行一个无限循环的Go协程(完成后重新启动)

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

Run a Go routine indefinitely (restart when done)

问题

我正在将我的TypeScript项目重写为Golang,并遇到了一个问题:

我正在运行一个for循环,在程序加载时启动异步工作器。如果我理解正确,Go协程是一种同时运行异步代码的方式。我想要做的是在函数完成后无限次地重新启动该函数。

在TypeScript中,代码看起来像这样:

async function init() {
  const count = await Users.getCount();

  // 同时运行所有工作器
  for (let i = 0; i < count; i += PER_WORKER) {
    const id = i / PER_WORKER;
    worker(id);
  }
}

async function worker(id: number) {
  await new Promise((resolve) => {
    // 做一些事情
    resolve();
  })

  // 重新启动函数
  worker(workerId);
}

在Go中,我有非常相似的代码,但在内部重新调用函数时会出现问题。我考虑过按时间间隔运行函数,但我无法预先知道它需要多长时间...

谢谢
NVH

英文:

I am rewriting my TypeScript projects to Golang and I encountered a problem:

I am running a for loop which starts up async workers on program load. If I understood correctly Go routines are a way to run async code concurrently. What I'd like to do is restart the function once it is done, indefinitely.

In TypeScript it looks something like

async function init() {
  const count = async Users.getCount();

  // run all workers concurrently
  for (let i = 0; i &lt; count; i += PER_WORKER) {
    const id = i / PER_WORKER;
    worker(id);
  }
}

async worker(id: number) {
  await new Promise((resolve) =&gt; {
    // do stuff
    resolve();
  })

  // restart function
  worker(workerId);
}

in Go I have pretty similar stuff, but when re-calling the function inside it just makes a mess? I thought of running the function by interval but I cannot know in advance the time it takes...

Thank you
NVH

答案1

得分: 6

我想做的是在函数完成后无限重启该函数。

你需要一个无限循环:

for {
    f()
}

如果你想要将无限循环分离出来,可以将其放在一个函数中,并使用go关键字调用它:

go func() {
    for {
        f()
    }
}()

也就是说,我们将for循环本身分离出来;for循环每次调用我们的函数一次。这样做:

for {
    go f()
}

是错误的,因为它会无限次地快速启动f(),而不等待f()返回。

英文:

> What I'd like to do is restart the function once it is done, indefinitely.

You need a forever loop, of course:

for {
    f()
}

If you want to spin off the forever loop itself, put that in a function and invoke it with go:

go func() {
    for {
        f()
    }
}()

That is, we spin off the for loop itself; the for loop calls our function once each time. Doing this:

for {
    go f()
}

is wrong because that spins off f() an infinite number of times, as fast as it can, without waiting for f() to return.

huangapple
  • 本文由 发表于 2022年7月2日 18:09:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/72838228.html
匿名

发表评论

匿名网友

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

确定