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标准库之sqlite3使用实例
Nov 25 Python
解决出现Incorrect integer value: '' for column 'id' at row 1的问题
Oct 29 Python
详解python eval函数的妙用
Nov 16 Python
浅谈Pycharm中的Python Console与Terminal
Jan 17 Python
简单了解python关系(比较)运算符
Jul 08 Python
使用Python代码实现Linux中的ls遍历目录命令的实例代码
Sep 07 Python
详解从Django Allauth中进行登录改造小结
Dec 18 Python
基于python实现微信好友数据分析(简单)
Feb 16 Python
Anaconda+Pycharm环境下的PyTorch配置方法
Mar 13 Python
python如何操作mysql
Aug 17 Python
python定时截屏实现
Nov 02 Python
Python道路车道线检测的实现
Jun 27 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
建立文件交换功能的脚本(一)
2006/10/09 PHP
php magic_quotes_gpc的一点认识与分析
2008/08/18 PHP
PHP实现自动登入google play下载app report的方法
2014/09/23 PHP
给PHP开发者的编程指南 第一部分降低复杂程度
2016/01/18 PHP
PHP实现的浏览器检查类
2016/04/11 PHP
mac下多个php版本快速切换的方法
2016/10/09 PHP
php实现和c#一致的DES加密解密实例
2017/07/24 PHP
PHP删除数组中指定下标的元素方法
2018/02/03 PHP
thinkPHP框架动态配置用法实例分析
2018/06/14 PHP
NodeJs基本语法和类型
2015/02/13 NodeJs
jQuery基于函数重载实现自定义Alert函数样式的方法
2016/07/27 Javascript
详解js的事件处理函数和动态创建html标记方法
2016/12/16 Javascript
JavaScript判断浏览器及其版本信息
2017/01/20 Javascript
js Canvas绘制圆形时钟教程
2017/02/06 Javascript
详解使用fetch发送post请求时的参数处理
2017/04/05 Javascript
利用Jasmine对Angular进行单元测试的方法详解
2017/06/12 Javascript
JavaScript使用Ajax上传文件的示例代码
2017/08/10 Javascript
jQuery Datatable 多个查询条件自定义提交事件(推荐)
2017/08/24 jQuery
angularJS的radio实现单项二选一的使用方法
2018/02/28 Javascript
jQuery实现带右侧索引功能的通讯录示例【附源码下载】
2018/04/17 jQuery
webpack proxy 使用(代理的使用)
2020/01/10 Javascript
小程序富文本提取图片可放大缩小
2020/05/26 Javascript
vue 实现把路由单独分离出来
2020/08/13 Javascript
[50:45]2018DOTA2亚洲邀请赛 4.6 淘汰赛 VP vs TNC 第一场
2018/04/10 DOTA
Python使用Pandas库实现MySQL数据库的读写
2019/07/06 Python
pytorch 可视化feature map的示例代码
2019/08/20 Python
python实现计算器功能
2019/10/31 Python
Python3常用内置方法代码实例
2019/11/18 Python
python开发入门——set的使用
2020/09/03 Python
matplotlib常见函数之plt.rcParams、matshow的使用(坐标轴设置)
2021/01/05 Python
New Balance澳大利亚官网:运动鞋和健身服装
2019/02/23 全球购物
优秀员工自荐书范文
2013/12/08 职场文书
改进作风怎么办发言材料
2014/08/17 职场文书
公司授权委托书范文
2014/09/21 职场文书
商务英语求职信范文
2015/03/19 职场文书
vue中 this.$set的使用详解
2021/11/17 Vue.js