Python进程,多进程,获取进程id,给子进程传递参数操作示例

yipeiwu_com6年前Python基础

本文实例讲述了Python进程,多进程,获取进程id,给子进程传递参数操作。分享给大家供大家参考,具体如下:

线程与线程之间共享全局变量,进程之间不能共享全局变量。
进程与进程相互独立  (可以通过socket套接字实现进程间通信,可以通过硬盘(文件)实现进程通信,也可以通过队列(Queue)实现进程通信)

子进程会拷贝复制主进程中的所有资源(变量、函数定义等),所以子进程比子线程耗费资源。

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()  # 多线程的方式实现多任务
  # t2.start()
  p1 = multiprocessing.Process(target=test1) # 进程 (进程比线程占用资源多)
  p2 = multiprocessing.Process(target=test2)
  p1.start()  # 多进程的方式实现多任务 (进程比线程占用资源多)
  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(给子进程传递参数):

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()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》、《Python+MySQL数据库程序设计入门教程》及《Python常见数据库操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python 遍历字符串(含汉字)实例详解

python 遍历字符串(含汉字)实例详解 s = "中国china" for j in s: print j 首先一个,你这个'a'是什么编码?可能不是你所想的gbk &...

Python pandas实现excel工作表合并功能详解

Python pandas实现excel工作表合并功能详解

import os,pandas as pd,re #1.获取文件夹下要合并的文件名 dirpath = '文件夹地址' #工作表3特殊处理 需要开始下标和结束下标 begin =...

使用memory_profiler监测python代码运行时内存消耗方法

使用memory_profiler监测python代码运行时内存消耗方法

前几天一直在寻找能够输出python函数运行时最大内存消耗的方式,看了一堆的博客和知乎,也尝试了很多方法,最后选择使用memory_profiler中的mprof功能来进行测量的,它的原...

Python 正则表达式入门(初级篇)

引子 首先说 正则表达式是什么? 正则表达式,又称正规表示式、正规表示法、正规表达式、规则表达式、常规表示法(英语:Regular Expression,在代码中常简写为regex、re...

Python实现的直接插入排序算法示例

Python实现的直接插入排序算法示例

本文实例讲述了Python实现的直接插入排序算法。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- '''直接插入的python实现 时间复杂度O(...