Python - 如何唤醒睡眠过程 - 多处理?

时间:2014-08-19 09:20:00

标签: python multiprocessing

我需要唤醒睡眠过程吗?

睡眠的时间(t)计算为t = D/S。既然s变化,可以增加或减少,我也需要增加/减少睡眠时间。通过UDP协议接收速度。那么,如何更改进程的休眠时间,请记住以下内容: -

If as per the previous speed `S1`, the time to sleep is `(D/S1)` . 
Now the speed is changed, it should now sleep for the new time,ie (D/S2). 
Since, it has already slept for D/S1 time, now it should sleep for D/S2 - D/S1.

我该怎么做?

截至目前,我只是假设整个计划的速度将保持不变,因此不会通知过程。但是,如果按照上述条件我该怎么做?

def process2():
    p = multiprocessing.current_process()
    time.sleep(secs1)
    # send some packet1 via UDP
    time.sleep(secs2)
    # send some packet2 via UDP
    time.sleep(secs3)
    # send some packet3 via UDP

另外,如在线程中,

1) threading.activeCount():返回活动的线程对象数。

2) threading.currentThread():返回调用者线程控件中的线程对象数。

3) threading.enumerate():返回当前活动的所有线程对象的列表。

在多处理中获取activecountenumerate有哪些相似的功能?

1 个答案:

答案 0 :(得分:1)

尚未测试,但我认为这可行:

  1. 不使用sleep,而是创建condition object并使用它的wait()方法。
  2. 创建一个Timer对象,在超时时调用条件对象的notify()方法。
  3. 如果您想更改睡眠时间,只需丢弃旧的Timer(使用cancel()方法),然后创建一个新的Timer。
  4. *更新*

    我刚试过这个并且有效。

    这是过程中的wait(),不要先伪造获取它。

    def process(condition):
        condition.acquire()
        condition.wait()
        condition.release()
    

    这是wake_up函数,从主进程调用:

    def wake_up(condition):
        condition.acquire()
        condition.notify()
        condition.release()
    

    在创建进程时创建并传递条件对象(在main或其他函数中):

        condition=multiprocessing.Condition(multiprocessing.Lock())
        p=multiprocessing.Process(target=process, args=(condition,))
        p.start()
    

    创建一个Timer(这个计时器线程将在主进程上创建):

        timer=threading.Timer(wake_up_time, wake_up, args(condition,))
        start_time=time.time()
        timer.start()
    

    如果你想改变时间,只需停下它并制作一个新的计时器:

        timer.cancel()
        elapsed_time=time.time-start_time
        timer=threading.Timer(new_wake_up_time-elapsed_time, wake_up, args(condition,))
        timer.start()
    
相关问题