python多进程参考代码
生活随笔
收集整理的這篇文章主要介紹了
python多进程参考代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#@Time : 2019/11/18 0018 21:55
#@Author : tb_youth
#@FileName: multiprocessingTest.py
#@SoftWare: PyCharm
#@Blog : https://blog.csdn.net/tb_youth'''
學習如何使用多進程
'''from multiprocessing import Process
import os
import timedef run_case(text):print('入參:{0},當前進程號:{1}'.format(text, os.getpid()))time.sleep(5)if __name__ == '__main__':#父進程用于啟動子進程print('當前是父進程,進程號:{0}'.format(os.getpid()))s1 = time.time()for i in range(5):child = Process(target=run_case, args=(str(i),))print('子進程啟動.')child.start()# join()進行進程阻塞(阻塞主進程,不加則會主進程結束再調用子進程)#目的是進程同步#但是不應該放在這里,應該放在所有start后面去執行#否則效率可能不如單進程child.join()e1 = time.time()print('time = {0}'.format(e1-s1))print('進程結束.')print('+------------------------+')print('當前是父進程,進程號:{0}'.format(os.getpid()))s2 = time.time()lst = []for i in range(5):child = Process(target=run_case, args=(i,))print('子進程啟動.')child.start()lst.append(child)# 多進程join()的正確寫法for child in lst:child.join()e2 = time.time()print('time = {0}'.format(e2 - s2))print('進程結束.')
執行上述代碼結果:
當前是父進程,進程號:3732 子進程啟動. 入參:0,當前進程號:8156 子進程啟動. 入參:1,當前進程號:7636 子進程啟動. 入參:2,當前進程號:7632 子進程啟動. 入參:3,當前進程號:3004 子進程啟動. 入參:4,當前進程號:16632 time = 26.717877864837646 進程結束. +------------------------+ 當前是父進程,進程號:3732 子進程啟動. 子進程啟動. 子進程啟動. 子進程啟動. 子進程啟動. 入參:3,當前進程號:17916 入參:2,當前進程號:13984 入參:1,當前進程號:17804 入參:0,當前進程號:3088 入參:4,當前進程號:3748 time = 5.643748760223389 進程結束.參考
總結
以上是生活随笔為你收集整理的python多进程参考代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: kali-linux nat模式下无法联
- 下一篇: python 判断类是否存在某个属性或方