我有问题需要使用多处理创建 python 进程线程 任何暂停它的时间 - 然后再恢复它 - 问题是这个逻辑可以在多线程上执行。
我尝试使用 Event 但我是 python 多处理的新手。
这是我创建的代码,但暂停/恢复不起作用 - 请帮忙:)?
import multiprocessing
def control_process(process):
"""
Receive a process object as an argument and provides the ability
to pause and resume the process.
"""
while True:
command = input("Enter 'p' to pause, 'r' to resume, or 'q' to quit: ")
print(command)
if command == "p":
process.set()
elif command == "r":
process.clear()
elif command == "q":
process.terminate()
break
import time
def my_function():
while True:
print("Hello, world!")
time.sleep(1)
if __name__ == "__main__":
p = multiprocessing.Process(target=my_function)
p.start()
control_process(p)
输出应该是
Start thread 1 ....
puase thread 1 ....
start thread 2 ....
Thread 2 ......
Thread 2 ......
End Thread 2 ....
End thread 1 ...
你应该为此使用一个 multiprocessing.Event,基本上你会把一个传递给孩子和控制线程并让它
set
它恢复和 clear
它暂停执行如下。
import multiprocessing
import time
def control_process(process, pause_event):
"""
Receive a process object as an argument and provides the ability
to pause and resume the process.
"""
while True:
command = input("Enter 'p' to pause, 'r' to resume, or 'q' to quit: ")
print(command)
if command == "p":
pause_event.clear()
elif command == "r":
pause_event.set()
elif command == "q":
process.terminate()
break
def my_function(pause_event, event_started):
event_started.set() # signal parent that it has started execution
while pause_event.wait(): # returns True if pause_event is set
print("Hello, world!")
time.sleep(1)
if __name__ == "__main__":
pause_event = multiprocessing.Event()
started_event = multiprocessing.Event() # to know when the child started execution
p = multiprocessing.Process(target=my_function, args=(pause_event, started_event))
p.start()
started_event.wait(timeout=5) # to fix window's buggy terminal
control_process(p, pause_event)
如果您在 Windows 上使用
started_event
,那么 input
的使用很重要,因为它会锁定整个终端,从而防止孩子在 input
功能结束之前产卵。
要使“p”(暂停)和“r”(恢复)工作,您可以使用 multiprocessing.Event
pause_event
而不是 process.
此外,无需再次打印命令,因为您可以在命令输入中看到它。
尝试以下代码:
import multiprocessing,time
def my_function(pause_event):
while True:
if not pause_event.is_set():
print("Hello, world!")
time.sleep(1)
if __name__ == "__main__":
pause_event = multiprocessing.Event()
pause_event.clear()
p = multiprocessing.Process(target=my_function, args=(pause_event,))
p.start()
while True:
command = input("Enter 'p' to pause, 'r' to resume, or 'q' to quit: ")
if command == "p":
pause_event.set()
elif command == "r":
pause_event.clear()
elif command == "q":
p.terminate()
break
if __name__ == "__main__":
p = multiprocessing.Process(target=my_function)
p.start()
control_process(p)
最后,如果你希望你的输出如你所愿,你应该为你的线程添加相应的打印。