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 相关文章推荐
windows下wxPython开发环境安装与配置方法
Jun 28 Python
17个Python小技巧分享
Jan 23 Python
关于python的bottle框架跨域请求报错问题的处理方法
Mar 19 Python
Python使用修饰器执行函数的参数检查功能示例
Sep 26 Python
python模拟表单提交登录图书馆
Apr 27 Python
python画图--输出指定像素点的颜色值方法
Jul 03 Python
python机器学习包mlxtend的安装和配置详解
Aug 21 Python
Spring实战之使用util:命名空间简化配置操作示例
Dec 09 Python
Python爬虫获取页面所有URL链接过程详解
Jun 04 Python
python向企业微信发送文字和图片消息的示例
Sep 28 Python
Python+Matplotlib图像上指定坐标的位置添加文本标签与注释
Apr 11 Python
Python tensorflow卷积神经Inception V3网络结构
May 06 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
提问的智慧(2)
2006/10/09 PHP
php面向对象全攻略 (三)特殊的引用“$this”的使用
2009/09/30 PHP
如何使用PHP计算上一个月的今天
2013/05/23 PHP
PHP static局部静态变量和全局静态变量总结
2014/03/02 PHP
Yii隐藏URL中index.php的方法
2016/07/12 PHP
Yii2.0表关联查询实例分析
2016/07/18 PHP
Mac版PhpStorm之XAMPP整合apache服务器配置的图文教程详解
2016/10/13 PHP
php5.3/5.4/5.5/5.6/7常见新增特性汇总整理
2020/02/27 PHP
禁止直接访问php文件代码分享
2020/05/05 PHP
让iframe框架网页在任何浏览器下自动伸缩
2006/08/18 Javascript
Jquery乱码的一次解决过程 图解教程
2010/02/20 Javascript
将光标定位于输入框最右侧实现代码
2012/12/04 Javascript
探讨:JavaScript ECAMScript5 新特性之get/set访问器
2016/05/05 Javascript
JavaScript数组的栈方法与队列方法详解
2016/05/26 Javascript
javascript实现用户点击数量统计
2016/12/25 Javascript
angular实现form验证实例代码
2017/01/17 Javascript
Vim快速合并行及vim 将文件所有行合并到一行
2017/11/27 Javascript
纯js代码生成可搜索选择下拉列表的实例
2018/01/11 Javascript
Vue源码探究之状态初始化
2018/11/14 Javascript
javascript中一些奇葩的日期换算方法总结
2018/11/14 Javascript
改变layer confirm弹窗按钮的颜色方法
2019/09/12 Javascript
layui 富文本赋值,取值,取纯文本值的实例
2019/09/18 Javascript
使用 Angular RouteReuseStrategy 缓存(路由)组件的实例代码
2019/11/01 Javascript
在vue中实现清除echarts上次保留的数据(亲测有效)
2020/09/09 Javascript
uniapp实现横向滚动选择日期
2020/10/21 Javascript
vue使用exif获取图片旋转,压缩的示例代码
2020/12/11 Vue.js
Python 中 list 的各项操作技巧
2017/04/13 Python
Python爬取qq空间说说的实例代码
2018/08/17 Python
Python逐行读取文件中内容的简单方法
2019/02/26 Python
Python实现堡垒机模式下远程命令执行操作示例
2019/05/09 Python
用Python+OpenCV对比图像质量的几种方法
2019/07/15 Python
Python基于BeautifulSoup和requests实现的爬虫功能示例
2019/08/02 Python
python中使用asyncio实现异步IO实例分析
2021/02/26 Python
职业生涯规划书结束语
2014/04/15 职场文书
出资证明书范本(标准版)
2014/09/24 职场文书
初中班主任培训心得体会
2016/01/07 职场文书