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+request+unittest实现接口测试框架集成实例

Python+request+unittest实现接口测试框架集成实例

1、为什么要写代码实现接口自动化 大家知道很多接口测试工具可以实现对接口的测试,如postman、jmeter、fiddler等等,而且使用方便,那么为什么还要写代码实现接口自动化呢?工...

python在Windows下安装setuptools(easy_install工具)步骤详解

python在Windows下安装setuptools(easy_install工具)步骤详解

本文讲述了python在Windows下安装setuptools(easy_install工具)的方法。分享给大家供大家参考,具体如下: 【题外话介绍下setuptools】 setup...

Python中BeautifuSoup库的用法使用详解

BeautifulSoup简介 Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。官方解释如下: Beautiful Soup提供一些简单的、pytho...

Python优化技巧之利用ctypes提高执行速度

首先给大家分享一个个人在使用python的ctypes调用c库的时候遇到的一个小坑 这次出问题的地方是一个C函数,返回值是malloc生成的字符串地址。平常使用也没问题,也用了有段时间,...

Python3实现将文件归档到zip文件及从zip文件中读取数据的方法

本文实例讲述了Python3实现将文件归档到zip文件及从zip文件中读取数据的方法。分享给大家供大家参考。具体实现方法如下: ''''' Created on Dec 24, 2...