python多进程并行代码
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)
本文来自博客园,作者:沉迷编程的程序员,转载请注明原文链接:https://www.cnblogs.com/codeDevotee/p/11610759.html
欢迎各位找我代写程序,python、c#、web等都可以,加我请注明博客园微信:A15919195482