欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python進程,多進程,獲取進程id,給子進程傳遞參數(shù)操作示例

 更新時間:2019年10月11日 10:54:30   作者:houyanhua1  
這篇文章主要介紹了Python進程,多進程,獲取進程id,給子進程傳遞參數(shù)操作,結(jié)合實例形式分析了Python多進程、父子進程以及進程參數(shù)傳遞相關(guān)操作技巧,需要的朋友可以參考下

本文實例講述了Python進程,多進程,獲取進程id,給子進程傳遞參數(shù)操作。分享給大家供大家參考,具體如下:

線程與線程之間共享全局變量,進程之間不能共享全局變量。
進程與進程相互獨立  (可以通過socket套接字實現(xiàn)進程間通信,可以通過硬盤(文件)實現(xiàn)進程通信,也可以通過隊列(Queue)實現(xiàn)進程通信)

子進程會拷貝復(fù)制主進程中的所有資源(變量、函數(shù)定義等),所以子進程比子線程耗費資源。

demo.py(多進程):

import threading  # 線程
import time
import multiprocessing  # 進程
def test1():
  while True:
    print("1--------")
    time.sleep(1)
def test2():
  while True:
    print("2--------")
    time.sleep(1)
def main():
  # t1 = threading.Thread(target=test1) # 線程
  # t2 = threading.Thread(target=test2)
  # t1.start()  # 多線程的方式實現(xiàn)多任務(wù)
  # t2.start()
  p1 = multiprocessing.Process(target=test1) # 進程 (進程比線程占用資源多)
  p2 = multiprocessing.Process(target=test2)
  p1.start()  # 多進程的方式實現(xiàn)多任務(wù) (進程比線程占用資源多)
  p2.start()
if __name__ == "__main__":
  main()

demo.py(獲取進程、父進程id):

import multiprocessing
import os
import time
def test():
  while True:
    print("----in 子進程 pid=%d ,父進程的pid=%d---" % (os.getpid(), os.getppid()))
    time.sleep(1)
def main():
  # os.getpid() 獲取當前進程的進程id
  # os.getppid() 獲取當前進程的父進程id
  print("----in 主進程 pid=%d---父進程pid=%d----" % (os.getpid(), os.getppid()))
  p = multiprocessing.Process(target=test)
  p.start() # 開啟子進程
if __name__ == "__main__":
  main()

demo.py(給子進程傳遞參數(shù)):

import multiprocessing
def test(a, b, c, *args, **kwargs):
  print(a) # 11
  print(b) # 22
  print(c) # 33
  print(args)  # (44, 55, 66, 77, 88)
  print(kwargs) # {'age': 20, 'name': '張三'}
def main():
  p = multiprocessing.Process(target=test, args=(11, 22, 33, 44, 55, 66, 77, 88), kwargs={"name": "張三","age": 20})
  p.start()
if __name__ == "__main__":
  main()

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python進程與線程操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》、《Python+MySQL數(shù)據(jù)庫程序設(shè)計入門教程》及《Python常見數(shù)據(jù)庫操作技巧匯總

希望本文所述對大家Python程序設(shè)計有所幫助。

相關(guān)文章

最新評論