Posted in Python onSeptember 30, 2019
这篇文章主要介绍了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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。
python多进程并行代码实例
- Author -
科技改变未来☆声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@