python 进程 进程池 进程间通信实现解析

yipeiwu_com6年前Python基础

1.python 中创建进程的两种方式:

from multiprocessing import Process
import time
def test_():
  print '-----test-----'
if __name__ == '__main__':
  p = Process(target=test_)
  p.start()
  while True:
    print '--main--'
    

'''1.通过process 类创建一个进程对象,然后start即可开启进程, test
test_函数是进程实现的功能'''
 
 from multiprocessing import Process
 import time
 class MyNewProcess(Process):
   def run(self):
     print '------run-------'
 if __name__ == '__main__':
   p = MyNewProcess()
   p.start()
   print '---main-----'
 '''2.通过类似继承process  子类中必须有run 方法 里边实现 进程功能 
 创建对象之后 调用start'''

2.进程池

from multiprocessing import Pool
from time import sleep
import os 
def func(num):
  for i in range(3):
    print '%s %s' %(os.getpid(),num) #
    sleep(2)
def main():
  pool = Pool(3)
  for i in range(3, 6):
    res = pool.apply_async(func, (i,))
  pool.close()
  pool.join() 
if __name__ == '__main__':
  main()

3.进程间通信

'''python 进程间通信   Queue '''

'''1.Queue使用方法
  1.Queue.qsize(): 返回当前队列包含的消息数量
  2.Queue.empty(): 如果队列为空 返回True 反之 False
  3.Queue.full(): 如果队列满了返回True 反之 False
  4.Queue.get():  获取队列中一条消息 然后将其从队列中移除 可传参数 超市时长
  Queue.get_nowait(): 相当于 Queue.get(False) 取不到值 触发异常
  Queue.put(): 将一个值添加到数列 可传参数 超时时长
  Queue.put_nowait():相当于 Queue.get(False) 当队列满时 报错
'''
from multiprocessing import Process, Queue
import time
q = Queue() # 创建队列
for i in range(10):
  q.put(i)    
def test_a():
    try:
      while True:
        num = q.get_nowait()
        print '我是进程a 取出数字为:%s'%num
        time.sleep(1)
    except Exception, e:
      print e
def test_b():
  try:
    while True:
      num = q.get_nowait()
      print '我是进程b 取出数字是:%s'%num
      time.sleep(1)
  except Exception, e:
    print e
if __name__ == '__main__':
  p1 = Process(target=test_a)
  p2 = Process(target=test_b)
  p1.start()
  p2.start()

至此 简单得使用已经结束

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python OpenCV之图片缩放的实现(cv2.resize)

Python OpenCV之图片缩放的实现(cv2.resize)

OpenCV函数原型: cv2.resize(InputArray src, OutputArray dst, Size, fx, fy, interpolation) 参数解释:...

探索Python3.4中新引入的asyncio模块

使用 Simple Protocol asyncio.BaseProtocol 类是asyncio模块中协议接口(protocol interface)的一个常见的基类。asyncio....

Python实现的用户登录系统功能示例

Python实现的用户登录系统功能示例

本文实例讲述了Python实现的用户登录系统功能。分享给大家供大家参考,具体如下: 有N,E,Q三个选择,若选择Q或者中断,则系统退出。若其他选项,则持续让用户选择。 #!/usr/...

python cx_Oracle模块的安装和使用详细介绍

python cx_Oracle模块的安装 最近需要写一个数据迁移脚本,将单一Oracle中的数据迁移到MySQL Sharding集群,在linux下安装cx_Oracle感觉还是有一...

Pycharm 设置默认头的图文教程

Pycharm 设置默认头的图文教程

1. 设置的路径是File->settings->Editor->File and Code Templates->Python Script内容见图: 这样新...