简体   繁体   English

一种非阻塞的扭曲睡眠/等待方式?

[英]A non blocking way to sleep/wait in twisted?

Is there a non-blocking way to wait or come back to this function within twisted? 有没有一种非阻塞方式可以在扭曲状态下等待或返回该功能?

I have a loop ticker that is just set to tick on a set interval and that is all working GREAT. 我有一个循环行情自动收录器,它仅设置为按设定的时间间隔进行tick ,并且一切正常。 However, when stopping it I want to make sure that it isn't currently in a Tick doing any work. 但是,停止它时,我想确保它当前不在Tick进行任何工作。 If it is I just want twisted to come back to it and kill it in a moment. 如果是的话,我只想扭曲回到那儿,然后杀死它。

def stop(self):
    import time
    while self.in_tick:
        time.sleep(.001) # Blocking
    self.active = False
    self.reset()
    self.timer.stop()

Sometimes this above function gets called while another thread is running a Tick operation and I want to finish the Tick and then come back and stop this. 有时,当另一个线程正在运行Tick操作时,会调用上面的函数,而我想完成Tick ,然后返回并停止它。

I DO NOT want to block the loop in anyway during this operation. 不想阻止此操作过程中无论如何循环。 How could I do so? 我该怎么办?

It looks a bit strange to do a time.sleep() instead of just waiting for an event to signal and fire a deferred to do what you want. 做一个time.sleep()看起来有点奇怪,而不是仅仅等待一个事件来发信号并触发一个延迟来做你想做的事情。 With threads you might wake up this thread, check 'self.in_tick == False' and before you reach 'self.active = False', the other thread starts the new tick, so this might have a race condition and may not work as you expect anyway. 对于线程,您可能会唤醒该线程,请检查“ self.in_tick == False”,然后在达到“ self.active = False”之前,另一个线程会启动新的滴答,因此这可能具有竞争条件,并且可能无法正常工作无论如何你都期望。 So hopefully you have some other thread synchronization somewhere to make it work. 因此,希望您可以在其他地方进行一些其他线程同步以使其工作。

You can try to split your code into two functions and have one that schedules itself if not done. 您可以尝试将代码分成两个功能,如果没有完成,可以安排一个功能自行计划。

def stop(self):
    # avoid reentracy
    if not self._stop_call_running:
        self._stop()

def _stop(self):
    if self.in_tick:
       # reschedule itself
       self._stop_call_running = reactor.callLater(0.001, self._stop)
       return
    self.active = False
    self.reset()
    self.timer.stop()
    self._stop_call_running = None

You might also look at twisted.internet.task.LoopingCall . 您可能还会看twisted.internet.task.LoopingCall

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM