Python - 如何唤醒一个休眠的进程-多进程?
我需要唤醒一个正在休眠的进程。
这个进程休眠的时间(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(): 返回当前所有活动线程的列表。
那么,在多进程中,有哪些类似的函数可以用来获取 activecount
和 enumerate
呢?
1 个回答
1
还没测试过,但我觉得这样做可能有效:
- 不要用 sleep,创建一个 条件对象,然后使用它的 wait() 方法。
- 创建一个 定时器 对象,当时间到时调用条件对象的 notify() 方法。
- 如果你想改变休眠时间,只需取消旧的定时器(用 cancel() 方法),然后创建一个新的定时器。
* 更新 *
我刚测试过,这个方法有效。
这是在进程中使用的 wait(),别忘了先获取它。
def process(condition):
condition.acquire()
condition.wait()
condition.release()
这是从主进程调用的 wake_up 函数:
def wake_up(condition):
condition.acquire()
condition.notify()
condition.release()
在创建进程时创建并传递一个条件对象(在你的主函数或其他函数中):
condition=multiprocessing.Condition(multiprocessing.Lock())
p=multiprocessing.Process(target=process, args=(condition,))
p.start()
创建一个定时器(这个定时器线程会在主进程中创建):
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()