Python3.5多进程原理与用法实例分析


Posted in Python onApril 05, 2019

本文实例讲述了Python3.5多进程原理与用法。分享给大家供大家参考,具体如下:

Python3.5多进程原理与用法实例分析

进程类:Process

Python3.5多进程原理与用法实例分析

示例及代码:

Python3.5多进程原理与用法实例分析

(1)创建函数作为单进程

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import multiprocessing
import time
#创建函数并将其作为单个进程
def worker(interval):
  n = 5    #进程数
  while n>0:
    print("The time is :{0}".format(time.ctime()))   #初始化时间
    time.sleep(interval)    #睡眠时间
    n-=1
if __name__ == "__main__":
  # 创建进程,target:调用对象,args:传参数到对象
  p = multiprocessing.Process(target=worker,args=(2,))
  p.start()    #开启进程
  print("进程号:",p.pid)
  print("进程别名:",p.name)
  print("进程存活状态:",p.is_alive())

运行结果:

进程号: 6784
进程别名: Process-1
进程存活状态: True
The time is :Wed Nov  1 10:59:03 2017
The time is :Wed Nov  1 10:59:05 2017
The time is :Wed Nov  1 10:59:07 2017
The time is :Wed Nov  1 10:59:09 2017
The time is :Wed Nov  1 10:59:11 2017

(2)创建函数作为多进程

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import multiprocessing
import time
#创建函数作为多进程
def work1(interval):
  print("work1...")
  time.sleep(interval)
  print("end work1...")
def work2(interval):
  print("work2...")
  time.sleep(interval)
  print("end work2...")
def work3(interval):
  print("work3...")
  time.sleep(interval)
  print("end work3...")
if __name__ == "__main__":
  p1 = multiprocessing.Process(target=work1,args=(1,))
  p2 = multiprocessing.Process(target=work2,args=(2,))
  p3 = multiprocessing.Process(target=work3,args=(3,))
  p1.start()
  p2.start()
  p3.start()
  print("The number of CPU is %d:"%(multiprocessing.cpu_count()))   #打印CPU核数
  for p in multiprocessing.active_children():     #循环打印子进程的名称和pid
    print("子进程名称:%s,子进程pid:%d" %(p.name,p.pid))
  print("ending....")

运行结果:

The number of CPU is 4:
子进程名称:Process-2,子进程pid:7108
子进程名称:Process-1,子进程pid:1896
子进程名称:Process-3,子进程pid:7952
ending....
work3...
work1...
work2...
end work1...
end work2...
end work3...

注:先运行主进程的内容,再运行子进程

(3)将进程定义成一个类

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import multiprocessing
import time
#将进程定义为一个类
class ClockProcess(multiprocessing.Process):
  def __init__(self,interval):
    multiprocessing.Process.__init__(self)   #重构了Process类里面的构造函数
    self.interval = interval
  def run(self):     #固定用run方法,启动进程自动调用run方法
    n = 5
    while n>0:
      print("The time is {0}".format(time.ctime()))
      time.sleep(self.interval)
      n-=1
if __name__ == "__main__":
  p = ClockProcess(2)
  p.start()

运行结果:

The time is Wed Nov  1 11:31:28 2017
The time is Wed Nov  1 11:31:30 2017
The time is Wed Nov  1 11:31:32 2017
The time is Wed Nov  1 11:31:34 2017
The time is Wed Nov  1 11:31:36 2017

(4)Queue(队列)实现多进程数据传输

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import multiprocessing
#Queue是多进程安全的队列,可以使用实现多进程之间的数据传递
def writer_proc(q):
  try:
    q.put(1,block=False)    #put方法插入数据到队列中
  except:
    pass
def reader_proc(q):
  try:
    print(q.get(block=False))    #get方法从队列中读取并删除一个元素
  except:
    pass
if __name__ == "__main__":
  q = multiprocessing.Queue()
  writer = multiprocessing.Process(target=writer_proc,args=(q,))
  writer.start()
  reader = multiprocessing.Process(target=reader_proc,args=(q,))
  reader.start()
  reader.join()
  writer.join()

运行结果:

1

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

Python 相关文章推荐
使用Python读写文本文件及编写简单的文本编辑器
Mar 11 Python
Python2.7下安装Scrapy框架步骤教程
Dec 22 Python
利用numpy和pandas处理csv文件中的时间方法
Apr 19 Python
PyTorch上搭建简单神经网络实现回归和分类的示例
Apr 28 Python
Python3.4 tkinter,PIL图片转换
Jun 21 Python
python实现二维插值的三维显示
Dec 17 Python
python Tkinter的图片刷新实例
Jun 14 Python
tensorflow之自定义神经网络层实例
Feb 07 Python
django restframework serializer 增加自定义字段操作
Jul 15 Python
python 实现性别识别
Nov 21 Python
在pycharm中使用pipenv创建虚拟环境和安装django的详细教程
Nov 30 Python
Python中非常使用的6种基本变量的操作与技巧
Mar 22 Python
Python选择网卡发包及接收数据包
Apr 04 #Python
详解Python的数据库操作(pymysql)
Apr 04 #Python
python dlib人脸识别代码实例
Apr 04 #Python
python图像处理入门(一)
Apr 04 #Python
python爬虫简单的添加代理进行访问的实现代码
Apr 04 #Python
Django项目中添加ldap登陆认证功能的实现
Apr 04 #Python
使用 Python 玩转 GitHub 的贡献板(推荐)
Apr 04 #Python
You might like
php的慢速日志引起的Mysql错误问题分析
2014/05/13 PHP
彻底删除thinkphp3.1案例blog标签的方法
2014/12/05 PHP
一个非常完美的读写ini格式的PHP配置类分享
2015/02/12 PHP
简单谈谈favicon
2015/06/10 PHP
php gd等比例缩放压缩图片函数
2016/06/12 PHP
php日志函数error_log用法实例分析
2019/09/23 PHP
Javascript 判断函数类型完美解决方案
2009/09/02 Javascript
javascript 打印内容方法小结
2009/11/04 Javascript
JS判断字符串字节数并截取长度的方法
2016/03/05 Javascript
Node.JS利用PhantomJs抓取网页入门教程
2017/05/19 Javascript
AngularJS表单验证功能分析
2017/05/26 Javascript
BootStrap Table 后台数据绑定、特殊列处理、排序功能
2017/05/27 Javascript
node.js-v6新版安装具体步骤(分享)
2017/09/06 Javascript
微信小程序页面缩放式侧滑效果的实现代码
2018/11/15 Javascript
Vue基础配置讲解
2019/11/29 Javascript
js判断浏览器的环境(pc端,移动端,还是微信浏览器)
2020/12/24 Javascript
python字典多条件排序方法实例
2014/06/30 Python
Python设计实现的计算器功能完整实例
2017/08/18 Python
Python中 传递值 和 传递引用 的区别解析
2018/02/22 Python
python2.7 json 转换日期的处理的示例
2018/03/07 Python
Python函数的参数常见分类与用法实例详解
2019/03/30 Python
Python 利用高德地图api实现经纬度与地址的批量转换
2019/08/14 Python
python生成13位或16位时间戳以及反向解析时间戳的实例
2020/03/03 Python
Python接口测试环境搭建过程详解
2020/06/29 Python
linux面试题参考答案(1)
2016/01/22 面试题
质量承诺书格式
2014/05/20 职场文书
教师对照四风自我剖析材料
2014/09/30 职场文书
工程服务质量承诺书
2015/04/29 职场文书
伊索寓言读书笔记
2015/06/30 职场文书
小学运动会入场口号
2015/12/24 职场文书
大学生社区义工服务心得体会
2016/01/22 职场文书
《藏戏》教学反思
2016/02/23 职场文书
浙江省杭州市平均工资标准是多少?
2019/07/09 职场文书
总结Pyinstaller打包的高级用法
2021/06/28 Python
springboot 启动如何排除某些bean的注入
2021/08/02 Java/Android
MySQL慢查询中的commit慢和binlog中慢事务的区别
2022/06/16 MySQL