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中正则表达式的用法总结

正则表达式很神奇啊 # -*- coding:utf-8 -*- import re def print_match_res(res): """打印匹配对象内容""" if...

python实现数通设备tftp备份配置文件示例

  环境:【wind2003[open Tftp server] + virtualbox:ubuntn10 server】tftp : Open TFTP Server&nb...

Python3的介绍、安装和命令行的认识(推荐)

Python3的介绍、安装和命令行的认识(推荐)

PYTHON3介绍 Python是著名的“龟叔”Guido van Rossum在1989年圣诞节期间,为了打发无聊的圣诞节而编写的一个编程语言。 Python就为我们提供了非常完善的基...

解决python3 urllib中urlopen报错的问题

解决python3 urllib中urlopen报错的问题

前言 最近更新了Python版本,准备写个爬虫,意外的发现urllib库中属性不存在urlopen,于是各种google,然后总结一下给出解决方案 问题的出现 Attribute...

python实现保存网页到本地示例

学习python示例:实现保存网页到本地复制代码 代码如下:#coding=utf-8__auther__ = 'xianbao'import urllibimport osdef re...