python 测试multiprocessing多进程
生活随笔
收集整理的這篇文章主要介紹了
python 测试multiprocessing多进程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 測試1 multiprocessing函數的調用
- 測試2 pipe
- 測試queue
測試1 multiprocessing函數的調用
# -*- coding: utf-8 -*- """ @File : 20200312_test_multiprocessing.py @Time : 2020/3/12 16:38 @Author : Dontla @Email : sxana@qq.com @Software: PyCharm """ import os import threading import multiprocessing# Main print('Main:', os.getpid())print('How are you!')# worker function def worker(sign, lock):lock.acquire()print(sign, os.getpid())lock.release()# Multi-thread # record = [] # lock = threading.Lock()# Multi-process record = [] lock = multiprocessing.Lock()if __name__ == '__main__':# for i in range(5):# thread = threading.Thread(target=worker, args=('thread', lock))# thread.start()# record.append(thread)## for thread in record:# thread.join()# 用multiprocessing調用一下函數就相當于重新導一下包(相當于它自己又開了個python?)for i in range(5):process = multiprocessing.Process(target=worker, args=('process', lock))process.start()record.append(process)for process in record:process.join()結果:
D:\20191031_tensorflow_yolov3\python\python.exe C:/Users/SIQI/Desktop/test_multiprocessing/20200312_test_multiprocessing.py Main: 22560 How are you! Main: 31028 How are you! Main: 30472 How are you! Main: 11780 How are you! process 31028 process 30472 process 11780 Main: 27904 How are you! Main: 30488 How are you! process 27904 process 30488Process finished with exit code 0測試2 pipe
# -*- coding: utf-8 -*- """ @File : 20200312_測試pipe.py @Time : 2020/3/13 9:16 @Author : Dontla @Email : sxana@qq.com @Software: PyCharm """ import multiprocessing as muldef proc1(pipe):pipe.send('hello')# print('proc1 rec:', pipe.recv())def proc2(pipe):print('proc2 rec:', pipe.recv())# pipe.send('hello, too')# Build a pipe pipe = mul.Pipe() print(len(pipe)) # 2if __name__ == '__main__':# Pass an end of the pipe to process 1p1 = mul.Process(target=proc1, args=(pipe[0],))# Pass the other end of the pipe to process 2p2 = mul.Process(target=proc2, args=(pipe[1],))p1.start()p2.start()p1.join()p2.join()結果:
D:\20191031_tensorflow_yolov3\python\python.exe C:/Users/SIQI/Desktop/test_multiprocessing/20200312_測試pipe.py 2 2 2 proc2 rec: helloProcess finished with exit code 0測試queue
參考文章1:Python multiprocessing使用詳解
參考文章2:Python多進程編程-進程間共享 對象
參考文章3:python 多進程multiprocessing 如何獲取子進程的返回值?進程池pool
參考文章4:關于python進程池先close再join的疑惑
總結
以上是生活随笔為你收集整理的python 测试multiprocessing多进程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 线程中start()与run()的区别
- 下一篇: 【植物大战僵尸2】算法 笔记