在GO中进行非阻滞睡眠
在C#中,当我们想在执行两个过程之间延迟时,我们有两个选项:
thread.sleep(time)
blocking等待task.delay(time)
是
换句话说,thread.sleep(time)
指定时间的当前线程时,等待task.delay(time)
暂停执行 线程(允许OS线程调度程序选择并运行更多线程),然后在指定的时间后恢复它。
在GO中,有time.sleep(time)
方法,该方法已知是阻止方法。假设我有一千个GO例程(因为Go具有自己的线程调度程序,而不是依靠OS调度程序,这不是一个问题),我想实现重试模式在这些过程中的每一个中,以这样的方式:
FOR 5 Times {
IF Request Fails
THEN
time.Sleep(time.Second * 30)
ELSE
RETURN
}
在这种情况下,使用time.sleep(time)
是安全的吗?还是有更好的方法?
编辑: 我不是在问time.sleep(time)
正在阻止!我不知道为什么我的问题是该帖子的重复!
In C# when we want to cause delay between the execution of two procedures we have two options:
Thread.Sleep(time)
which is blockingawait Task.Delay(time)
which is non-blocking
In other words, Thread.Sleep(time)
blocks the current thread for the specified time while await Task.Delay(time)
suspends the executing
thread (allowing the OS thread scheduler to select and run more threads) and then it resumes it after the specified time.
In Go, there is time.Sleep(time)
method which is known to be a blocking method. Being new to Go, I have this question, assuming I have a thousand of go routines (since go has it's own thread scheduler instead of relying on the OS scheduler, this should not be a problem) and I would like to implement a retry pattern in each one of these go routines in such a way that:
FOR 5 Times {
IF Request Fails
THEN
time.Sleep(time.Second * 30)
ELSE
RETURN
}
Would it be safe to use time.Sleep(time)
in this case? Or is there a better way?
Edit:
I am not asking if time.Sleep(time)
is blocking!! I have no I idea why my question is duplicate of that post!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
GO中没有异步/等待。要有一个非障碍睡眠,您必须将其包裹在goroutine中。然后,它可以使用频道消息将结果归还到主要上下文。
There's no async/await in go. To have a non-blocking sleep you have to wrap it in a goroutine. Then it can return its result to the main context using a channel message.
如果您希望goroutine等待特定的时间,
time.sleep.sleep
是最好,最正确的方法。If you want a goroutine to wait for a specific amount of time,
time.Sleep
is the best, most correct way to do that.