英文:
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 < count; i += PER_WORKER) {
const id = i / PER_WORKER;
worker(id);
}
}
async worker(id: number) {
await new Promise((resolve) => {
// 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论