一种方法是使用可选的超时参数
Process.join()
方法接受。这将使它最多只能阻塞该时间长度的调用线程。
我还设置了
daemon
属性,以便主线程能够终止,即使它启动的某个进程仍在“运行”(或已挂起)。
最后一点,你不需要
multiprocessing.Lock
控制访问a
multiprocessing.Queue
,因为他们自动处理这方面的事情,所以我删除了它。出于某些其他原因,您可能仍然希望有一个标准输出,例如控制对标准输出的访问,以便从各个进程打印到标准输出不会重叠,也不会弄乱输出到屏幕的内容。
import multiprocessing
from multiprocessing import Process
import time
import datetime
def start_SAP():
print 'opening SAP program'
def report_1(q):
while True:
if q.empty():
time.sleep(1)
else:
k = q.get()
time.sleep(1)
break
print 'report 1 finished'
def report_2(q):
while True:
if q.empty():
time.sleep(1)
else:
k = q.get()
time.sleep(1)
break
print 'report 2 finished'
def report_3(q):
while True:
if q.empty():
time.sleep(1)
else:
k = q.get()
time.sleep(60000)
break
print 'report 3 finished'
def report_N(q):
while True:
if q.empty():
time.sleep(1)
else:
k = q.get()
time.sleep(1)
break
print 'report N finished'
def close_SAP():
print 'closing SAP'
def format_file():
print 'formatting files'
def multi_daily_pull():
shared_list = range(6)
q = multiprocessing.Queue()
for n in shared_list:
q.put(n)
print 'Starting process at ', time.strftime('%m/%d/%Y %H:%M:%S')
print 'Starting SAP Pulls at ', time.strftime('%m/%d/%Y %H:%M:%S')
StartSAP = Process(target=start_SAP)
StartSAP.start()
StartSAP.join()
report1 = Process(target=report_1, args=(q,))
report1.daemon = True
report2 = Process(target=report_2, args=(q,))
report2.daemon = True
report3 = Process(target=report_3, args=(q,))
report3.daemon = True
reportN = Process(target=report_N, args=(q,))
reportN.daemon = True
report1.start()
report2.start()
report3.start()
reportN.start()
report1.join(30)
report2.join(30)
report3.join(30)
reportN.join(30)
EndSAP = Process(target=close_SAP)
EndSAP.start()
EndSAP.join()
formatfile = Process(target=format_file)
formatfile .start()
formatfile .join()
if __name__ == '__main__':
multi_daily_pull()