小编给大家分享一下python中多进程并行的示例分析,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
创新互联建站是一家专注于成都做网站、成都网站建设与策划设计,贡井网站建设哪家好?创新互联建站做网站,专注于网站建设10余年,网设计领域的专业建站公司;建站业务涵盖:贡井等地区。贡井做网站价格咨询:18980820575代码:
from multiprocessing import Process import sys, os import time def timetask(string): while True: print(string) def works(func, arg, worknum): proc_record = [] for i in range(worknum): p = Process(target = func, args = (i,)) p.start() proc_record.append(p) for p in proc_record: p.join() if __name__ == '__main__': arg = 5 procs = 4 works(timetask, arg, procs)
效果图【未加锁,会发现数字1没出现,进程间资源抢夺导致】:
优化之后效果:
代码:
from multiprocessing import Process import sys, os import time from threading import Lock def timetask(string): mutex.acquire() while True: print(string) if mutex.locked(): mutex.release() mutex = Lock() def works(func, arg, worknum): proc_record = [] for i in range(worknum): p = Process(target = func, args = (i,)) p.start() proc_record.append(p) for p in proc_record: p.join() if __name__ == '__main__': arg = 5 procs = 4 works(timetask, arg, procs)
看完了这篇文章,相信你对“python中多进程并行的示例分析”有了一定的了解,如果想了解更多相关知识,欢迎关注创新互联行业资讯频道,感谢各位的阅读!