标签:python BMI start ali port pool 继承方式 for import
1、进程
import multiprocessing import threading 1、进程间的数据不共享 data_list = [] def task(arg): data_list.append(arg) print(data_list) def run(): for i in range(10): p = multiprocessing.Process(target=task,args=(i,)) # p = threading.Thread(target=task,args=(i,)) p.start() if __name__ == ‘__main__‘: run() 2、通过继承方式创建进程 class MyProcess(multiprocessing.Process): def run(self): print(‘当前进程‘,multiprocessing.current_process()) def run(): p1 = MyProcess() p1.start() p2 = MyProcess() p2.start() if __name__ == ‘__main__‘: run()
2、进程数据共享
import multiprocessing import threading import queue import time 进程间的数据共享:multiprocessing.Queue q = multiprocessing.Queue() def task(arg,q): q.put(arg) def run(): for i in range(10): p = multiprocessing.Process(target=task, args=(i, q,)) p.start() while True: v = q.get() print(v) run() 进程间的数据共享:Manager def task(arg,dic): time.sleep(2) dic[arg] = 100 if __name__ == ‘__main__‘: m = multiprocessing.Manager() process_list = [] for i in range(10): p = multiprocessing.Process(target=task, args=(i,dic,)) p.start() process_list.append(p) while True: count = 0 for p in process_list: if not p.is_alive(): count += 1 if count == len(process_list): break print(dic)
3、进程锁
import time import threading import multiprocessing lock = multiprocessing.RLock() def task(arg): print(‘鬼子来了‘) lock.acquire() time.sleep(2) print(arg) lock.release() if __name__ == ‘__main__‘: p1 = multiprocessing.Process(target=task,args=(1,)) p1.start() p2 = multiprocessing.Process(target=task, args=(2,)) p2.start()
4、进程池
import time from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor def task(arg): time.sleep(2) print(arg) if __name__ == ‘__main__‘: pool = ProcessPoolExecutor(5) for i in range(10): pool.submit(task,i)
import time from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor def task(arg): time.sleep(2) print(arg) if __name__ == ‘__main__‘: pool = ProcessPoolExecutor(5) for i in range(10): pool.submit(task,i)
标签:python BMI start ali port pool 继承方式 for import
原文地址:https://www.cnblogs.com/P-Z-W/p/11218249.html