广告
返回顶部
首页 > 资讯 > 后端开发 > Python >关于python multiproces
  • 846
分享到

关于python multiproces

pythonmultiproces 2023-01-31 07:01:28 846人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

这两天温故了python 的multiprocessing多进程模块,看到的pipe和queue这两种ipc方式,啥事ipc? ipc就是进程间的通信模式,常用的一半是socke,rpc,pipe和消息队列等。 今个就再把pipe和queu


这两天温故了python 的multiprocessing多进程模块,看到的pipe和queue这两种ipc方式,啥事ipc? ipc就是进程间的通信模式,常用的一半是socke,rpc,pipe和消息队列等。 


今个就再把pipe和queue搞搞。

#coding:utf-8
import multiprocessing
import time

def proc1(pipe):
    while True:
        for i in xrange(10000):
            print "发送 %s"%i
            pipe.send(i)
            time.sleep(1)

def proc2(pipe):
    while True:
        print 'proc2 接收:',pipe.recv()
        time.sleep(1)

def proc3(pipe):
    while True:
        print 'proc3 接收:',pipe.recv()
        time.sleep(1)
# Build a pipe
pipe = multiprocessing.Pipe()
print pipe

# Pass an end of the pipe to process 1
p1   = multiprocessing.Process(target=proc1, args=(pipe[0],))
# Pass the other end of the pipe to process 2
p2   = multiprocessing.Process(target=proc2, args=(pipe[1],))


p1.start()
p2.start()
p1.join()
p2.join()
#原文: Http://rfyiamcool.blog.51cto.com/1030776/1549857


wKiom1QMg-eDtFxLAAGBtG0nAh8373.jpg


不只是multiprocessing的pipe,包括其他的pipe实现,都只是两个进程之间的游玩,我给你,你来接收 或者是你来,我接收。 当然也可以做成双工的状态。  


queue的话,可以有更多的进程参与进来。用法和一些别的queue差不多。


看下官网的文档:


multiprocessing.Pipe([duplex])

Returns a pair (conn1, conn2) of Connection objects representing the ends of a pipe.

#两个pipe对象。用这两个对象,来互相的交流。 


If duplex is True (the default) then the pipe is bidirectional. If duplex is False then the pipe is unidirectional: conn1 can only be used for receiving messages and conn2 can only be used for sending messages.


class multiprocessing.Queue([maxsize])

Returns a process shared queue implemented using a pipe and a few locks/semaphores. When a process first puts an item on the queue a feeder thread is started which transfers objects from a buffer into the pipe.

#队列的最大数


The usual Queue.Empty and Queue.Full exceptions from the standard library’s Queue module are raised to signal timeouts.


Queue implements all the methods of Queue.Queue except for task_done() and join().


qsize()

Return the approximate size of the queue. Because of multithreading/multiprocessing semantics, this number is not reliable.

#队列的大小


Note that this may raise NotImplementedError on Unix platfORMs like Mac OS X where sem_getvalue() is not implemented.


empty()

Return True if the queue is empty, False otherwise. Because of multithreading/multiprocessing semantics, this is not reliable.

#是否孔了。 如果是空的,他回返回一个True 的状态。 


full()

Return True if the queue is full, False otherwise. Because of multithreading/multiprocessing semantics, this is not reliable.

#队列的状态是否满了。 


put(obj[, block[, timeout]])

Put obj into the queue. If the optional argument block is True (the default) and timeout is None (the default), block if necessary until a free slot is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Queue.Full exception if no free slot was available within that time. Otherwise (block is False), put an item on the queue if a free slot is immediately available, else raise the Queue.Full exception (timeout is ignored in that case).

#塞入队列,可以加超时的时间。 


#文章原文: http://rfyiamcool.blog.51cto.com/1030776/1549857 


put_nowait(obj)

Equivalent to put(obj, False).

#这里是不堵塞的


get([block[, timeout]])

Remove and return an item from the queue. If optional args block is True (the default) and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Queue.Empty exception if no item was available within that time. Otherwise (block is False), return an item if one is immediately available, else raise the Queue.Empty exception (timeout is ignored in that case).

#获取状态


get_nowait()

Equivalent to get(False).

#不堵塞的get队列里面的数据


Queue has a few additional methods not found in Queue.Queue. These methods are usually unnecessary for most code:


close()

Indicate that no more data will be put on this queue by the current process. The background thread will quit once it has flushed all buffered data to the pipe. This is called automatically when the queue is garbage collected.

#关闭,省当前进程的资源。 

 

我配置了multiprocessing队里长度是3个,然后当我放入的是第四个的时候, 会发现一只的堵塞,他是在等待,有人把数据get掉一个,那个时候 他才能继续的塞入 。如果用put_nowait()的话,队列超出会立马会一个error的。


/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/queues.pyc in put_nowait(self, obj)


/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/queues.pyc in put(self, obj, block, timeout)


wKioL1QMjmuR30vjAAOEnmz0ElE220.jpg



下面是一段测试的代码,同学们可以跑跑demo,感受下。 

#coding:utf-8
import os
import multiprocessing
import time
# 写入 worker
def inputQ(queue):
    while True:
        info = "进程号 %s : 时间: %s"%(os.getpid(),int(time.time()))
        queue.put(info)
        time.sleep(1)
# 获取 worker
def outputQ(queue,lock):
    while True:
        info = queue.get()
#        lock.acquire()
        print (str(os.getpid()) + '(get):' + info)
#        lock.release()
        time.sleep(1)
#===================
# Main
record1 = []   # store input processes
record2 = []   # store output processes
lock  = multiprocessing.Lock()    # To prevent messy print
queue = multiprocessing.Queue(3)

# input processes
for i in range(10):
    process = multiprocessing.Process(target=inputQ,args=(queue,))
    process.start()
    record1.append(process)

# output processes
for i in range(10):
    process = multiprocessing.Process(target=outputQ,args=(queue,lock))
    process.start()
    record2.append(process)


wKiom1QMigmjsp8LAANICa7A4dI435.jpg



好了,简单讲讲了 pipe和queue的用法。 其实我今个本来想扯扯python pipe的,结果Google一搜,看到了multiprocessing的pipe。写完了pipe后,感觉文章的内容太少了,所以我才额外的增加了queue的。。。 


还有:  大家中秋节快乐 ~

--结束END--

本文标题: 关于python multiproces

本文链接: https://www.lsjlt.com/news/191138.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 关于python multiproces
    这两天温故了python 的multiprocessing多进程模块,看到的pipe和queue这两种ipc方式,啥事ipc? ipc就是进程间的通信模式,常用的一半是socke,rpc,pipe和消息队列等。 今个就再把pipe和queu...
    99+
    2023-01-31
    python multiproces
  • 关于python和sudo python
    之前在搞ssd的时候没出问题,后来重装啦一下系统,把它拷回来,发现出了点问题,在训练或者测试的时候,需要输入:python examples/ssd/ssd_pascal.py 或者python examples/ssd/score_ss...
    99+
    2023-01-31
    python sudo
  • 关于Python的JSON
    1、json模块load/loads、dump/dumps区别:(摘自这里)实际上json就是python字典的字符串表示,但是字典作为一个复杂对象是无法直接转换成定义它的代码的字符串,python有一个叫 simplejson的库可以方便...
    99+
    2023-01-31
    Python JSON
  • Python - 关于Python的变量
    Python的变量是动态的,不需要预先申明,当赋值时自动创建变量,并且Python变量存储的是对象的引用(非变量本身)。Python变量的命名规则与C语言相似,并且在日常使用中一般会遵循以下一些规则:A. 一般不以单下划线“_”开头,因为以...
    99+
    2023-01-31
    变量 Python
  • 关于python测试webservice
    现在大公司非常流行用python做产品的测试框架,还有对于一些快速原型产品的开发也好,很好地支持OO编程,代码易读。Python的更新挺快的,尤其是第三方库。对于测试人员,代码基础薄弱,用python语言容易上手。今天就python测试we...
    99+
    2023-01-31
    测试 python webservice
  • python关于Mysql操作
    一.安装mysqlwindows下,直接下载mysql安装文件,双击安装文件下一步进行操作即可,下载地址:http://dev.mysql.com/downloads/mysql/Linux下的安装也很简单,除了下载安装包进行安装外,一般的...
    99+
    2023-01-31
    操作 python Mysql
  • 关于python中的setup.py
    目录1. 为什么需要对项目分发打包2. 包分发的始祖:distutils3. 分发工具升级:setuptools4. easy_install 使用指南5. 源码包与二进制包什么区别...
    99+
    2022-11-11
  • 关于python的索引
    写了几天程序,深刻地感受到python语言中(特指numpy、pandas)对于数据强大的索引能力。特此总结一下: iloc和loc的区别https://www.cnblogs.com/ghllfl/p/8481576.html loc:通...
    99+
    2023-01-31
    索引 python
  • Python中关于list、tuple、
    List定义及常用的方法见上一篇博客。 Tuple元组tuple的定义:            tuple是一个有序的元素组成的不可变对象的集合,使用小括号()表示,是可迭代对象 元组中数据的访问            支持索引(下标访问)...
    99+
    2023-01-31
    Python list tuple
  • 关于python中 __init__.p
    python   __init__.py  常见的情况中,我们将自己写好的代码转化为函数的话去调用的话,都是事先写好一个.py结尾的文件,将这个文件copy到当前目录下,或者是在python的sys.path中事先定义好的路径中去。之后在另...
    99+
    2023-01-31
    python
  • 关于python的doc string
    PEP 257 (http://www.python.org/peps/pep-0257.html) 定义了 doc string规范。Python Style Guide (http://www.python.org/doc/essays...
    99+
    2023-01-31
    python doc string
  • 关于Python的Type,Module
    关于Python的Type,Module,ClassPosted on 2007-07-13 by jeff 类在Python中只是一种数据类型.而任何东西都是对象应该是针对Type来说的,对象是Type的实例,而并不限于是类的实例.要知道...
    99+
    2023-01-31
    Python Type Module
  • 关于python列表相关知识点
    目录python列表1.列表的创建与删除列表的特点1.列表元素按顺序有序排序2.索引映射唯一数据3.列表可以存储重复数据4.任意数据类型混存5.根据需要动态分配和回收内存2.列表的查...
    99+
    2023-05-16
    python python列表
  • 关于Python 内置库 itertools
    目录1、itertools库2、使用itertools3、itertools.accumulate4、itertools.chain5、itertools.combinations_...
    99+
    2022-11-12
  • python 关于epoll的学习
          在linux中,默认情况下所有的socket都是blocking;当 用户进程调用了recvfrom这个系统调用,kernel就开始了IO的第一个阶段:准备数据。对于network io来说,很多时候数据在一开始还没有到达(比...
    99+
    2023-01-31
    python epoll
  • 关于python类SortedList详解
    目录SortedList 有序序列方法1.添加值2.移除值3.查找4.迭代值5. 其他SortedList 有序序列 class sortedcontainers.SortedL...
    99+
    2022-11-12
  • 23:python中关于缩进
    23.1 缩进的思考                              参考20.1.2  为什么第一条print语句(第11行)参与while循环,打印多次。而,第二条print语句(第15行)不参与循环只打印一次?  难道是第1...
    99+
    2023-01-31
    python
  • 关于B+tree (附python 模
    前几天我写了点btree的东西(http://thuhak.blog.51cto.com/2891595/1261783),今天继续这个思路,继续写b+tree。而且b+tree才是我的目的,更加深入理解文件和数据库索引的基本原理。在之前,...
    99+
    2023-01-31
    tree python
  • python关于return的用法
    在我们看来return就是返回值得意思,但是就我而言 我觉得自己太粗心大意了, return是返回一个方法的值,如果你没有定义一个方法却用return 去返回这就大错特错了 官方文档中提示: The key word "return" w...
    99+
    2023-01-31
    python return
  • 关于python类的组合
    关于python类的组合,绞尽脑汁之后,写了一个生活中的简单例子,有需要的童鞋可以理解下,水平有限,不对的地方望指正 #coding:utf-8 class Engine():#某发动机厂家描述发动机对象def init(self, eng...
    99+
    2023-01-31
    组合 python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作