import multiprocessing as mp .
from multiprocessing import Process, Queue, Manager .
from threading import Thread .
from subprocess import Popen, PIPE, STDOUT .
count = 0
def loop1():
while True:
for i in range(0, 100):
count = count + 1 .
time.sleep(2)
if count == 100:
count = 0
def worker(filename):
proc = Popen(["{0}".format(filename)], stdout=PIPE, stderr=STDOUT, shell=True)
(proc.communicate()[0])
def loop2():
while True:
for i in ["a.py", "b.py"]:
if count == 50:
# run some executable in background and do not wait for it .
p = Process(target=worker, args=(i)) .
a.sleep(2)
if __name__ == '__main__':
T1 = Thread(target=loop1, args=())
T2 = Thread(target=loop2, args=())
T1.start() .
T2.start() .
#T1.join() .
#T2.join()
1( 我应该如何并行启动两个方法?我需要检查方法2中方法1的变量状态?T1.start((和T2.start。
2( loop2的任务必须在50秒后再次运行。
您需要使用Event来同步进程。对于多处理,这两个进程都将在一个单独的python实例中启动,因此它应该会给您很好的时间。看看下面的代码:
from multiprocessing import Process, Event
import os
import time
def task(event, rerun=None):
proc_id = os.getpid()
event.wait() # Wait for an event
print('timestamp of process id {}: {}'.format(proc_id, time.time()))
if rerun is not None:
time.sleep(rerun)
print('timestamp of process id {}: {}'.format(proc_id, time.time()))
if __name__ == '__main__':
e = Event() # Create event that will be used for synchronization
p1 = Process(target=task, args=(e,))
p1.start()
# Start second task with rerun after 2 seconds
p2 = Process(target=task, args=(e, 2))
p2.start()
e.set() # Set event so all processes can start at the same time
这将产生这样的输出:
timestamp of process id 28415: 1542278592.7580822
timestamp of process id 28416: 1542278592.7585154
timestamp of process id 28416: 1542278594.7604039
至于其他事情,只需玩这个代码