首页 > 解决方案 > Python如何让操作系统阻止进程并按计时器恢复

问题描述

我一直在环顾四周,似乎找不到一个模块可以让我在计时器完成之前阻止当前进程。我不想做的是在等待(忙等待)时利用 CPU。我希望该进程被操作系统阻止/暂停,并在计时器完成时自动通知。

    # use a system call to create a waitable timer
    timer = CreateWaitableTime()

    # use another system call that waits on a waitable object
    WaitFor(timer)  # this will block the current process until the timer is signaled

    # .. sometime in the future, the timer might expire and it's object will be signaled
    #    causing the WaitFor(timer) call to resume operation
    do_other_stuff() # after timer

编辑这样做的原因是我将让另一个进程产生这些进程,因此这些进程是否被阻止并不重要。他们需要能够等待而不浪费 CPU 时间。

标签: python-3.x

解决方案


from threading import Event

evnt = Event()

wait_for = 5 #seconds
evnt.wait(wait_for) # will block for 5 seconds, or unless set early

另一个线程可以调用set以提前完成上面的等待

evnt.set()

推荐阅读