python 管道隊列_關于python:Multiprocessing-管道與隊列

Python的多處理程序包中的隊列和管道之間的根本區別是什么?

在什么情況下應該選擇一種? 什么時候使用Pipe()有優勢? 什么時候使用Queue()有優勢?

Pipe()只能有兩個端點。

Queue()可以有多個生產者和消費者。

何時使用它們

如果需要兩個以上的點進行通信,請使用Queue()。

如果您需要絕對性能,則Pipe()會更快,因為Queue()是建立在Pipe()之上的。

績效基準

假設您要生成兩個進程并在它們之間盡快發送消息。這些是使用Pipe()和Queue()進行的類似測試之間的拖動競賽的計時結果。這是在運行Ubuntu 11.10和Python 2.7.2的ThinkpadT61上進行的。

僅供參考,我將JoinableQueue()的結果作為獎勵; JoinableQueue()在調用queue.task_done()時負責任務(它甚至不知道特定任務,它只計算隊列中未完成的任務),因此queue.join()知道工作已完成。

此答案底部的每個代碼...

mpenning@mpenning-T61:~$ python multi_pipe.py

Sending 10000 numbers to Pipe() took 0.0369849205017 seconds

Sending 100000 numbers to Pipe() took 0.328398942947 seconds

Sending 1000000 numbers to Pipe() took 3.17266988754 seconds

mpenning@mpenning-T61:~$ python multi_queue.py

Sending 10000 numbers to Queue() took 0.105256080627 seconds

Sending 100000 numbers to Queue() took 0.980564117432 seconds

Sending 1000000 numbers to Queue() took 10.1611330509 seconds

mpnening@mpenning-T61:~$ python multi_joinablequeue.py

Sending 10000 numbers to JoinableQueue() took 0.172781944275 seconds

Sending 100000 numbers to JoinableQueue() took 1.5714070797 seconds

Sending 1000000 numbers to JoinableQueue() took 15.8527247906 seconds

mpenning@mpenning-T61:~$

總結Pipe()大約是Queue()的三倍。除非您確實必須擁有這些好處,否則甚至不要考慮JoinableQueue()。

獎勵材料2

除非您知道一些捷徑,否則多處理會在信息流中引入微妙的變化,使調試變得困難。例如,在許多情況下,當您通過字典建立索引時,您的腳本可能運行良好,但是某些輸入很少會失敗。

通常,當整個python進程崩潰時,我們會獲得有關失敗的線索;但是,如果多處理功能崩潰,則不會在控制臺上打印未經請求的崩潰回溯。很難找到未知的多處理崩潰,而又不知道導致進程崩潰的線索。

我發現跟蹤多處理崩潰信息的最簡單方法是將整個多處理功能包裝在try / except中并使用traceback.print_exc():

import traceback

def reader(args):

try:

# Insert stuff to be multiprocessed here

return args[0]['that']

except:

print"FATAL: reader({0}) exited while multiprocessing".format(args)

traceback.print_exc()

現在,當您發現崩潰時,您會看到類似以下內容的信息:

FATAL: reader([{'crash', 'this'}]) exited while multiprocessing

Traceback (most recent call last):

File"foo.py", line 19, in __init__

self.run(task_q, result_q)

File"foo.py", line 46, in run

raise ValueError

ValueError

源代碼:

"""

multi_pipe.py

"""

from multiprocessing import Process, Pipe

import time

def reader_proc(pipe):

## Read from the pipe; this will be spawned as a separate Process

p_output, p_input = pipe

p_input.close() ? ?# We are only reading

while True:

msg = p_output.recv() ? ?# Read from the output pipe and do nothing

if msg=='DONE':

break

def writer(count, p_input):

for ii in xrange(0, count):

p_input.send(ii) ? ? ? ? ? ? # Write 'count' numbers into the input pipe

p_input.send('DONE')

if __name__=='__main__':

for count in [10**4, 10**5, 10**6]:

# Pipes are unidirectional with two endpoints: ?p_input ------> p_output

p_output, p_input = Pipe() ?# writer() writes to p_input from _this_ process

reader_p = Process(target=reader_proc, args=((p_output, p_input),))

reader_p.daemon = True

reader_p.start() ? ? # Launch the reader process

p_output.close() ? ? ? # We no longer need this part of the Pipe()

_start = time.time()

writer(count, p_input) # Send a lot of stuff to reader_proc()

p_input.close()

reader_p.join()

print("Sending {0} numbers to Pipe() took {1} seconds".format(count,

(time.time() - _start)))

"""

multi_queue.py

"""

from multiprocessing import Process, Queue

import time

import sys

def reader_proc(queue):

## Read from the queue; this will be spawned as a separate Process

while True:

msg = queue.get() ? ? ? ? # Read from the queue and do nothing

if (msg == 'DONE'):

break

def writer(count, queue):

## Write to the queue

for ii in range(0, count):

queue.put(ii) ? ? ? ? ? ? # Write 'count' numbers into the queue

queue.put('DONE')

if __name__=='__main__':

pqueue = Queue() # writer() writes to pqueue from _this_ process

for count in [10**4, 10**5, 10**6]:

### reader_proc() reads from pqueue as a separate process

reader_p = Process(target=reader_proc, args=((pqueue),))

reader_p.daemon = True

reader_p.start() ? ? ? ?# Launch reader_proc() as a separate python process

_start = time.time()

writer(count, pqueue) ? ?# Send a lot of stuff to reader()

reader_p.join() ? ? ? ? # Wait for the reader to finish

print("Sending {0} numbers to Queue() took {1} seconds".format(count,

(time.time() - _start)))

"""

multi_joinablequeue.py

"""

from multiprocessing import Process, JoinableQueue

import time

def reader_proc(queue):

## Read from the queue; this will be spawned as a separate Process

while True:

msg = queue.get() ? ? ? ? # Read from the queue and do nothing

queue.task_done()

def writer(count, queue):

for ii in xrange(0, count):

queue.put(ii) ? ? ? ? ? ? # Write 'count' numbers into the queue

if __name__=='__main__':

for count in [10**4, 10**5, 10**6]:

jqueue = JoinableQueue() # writer() writes to jqueue from _this_ process

# reader_proc() reads from jqueue as a different process...

reader_p = Process(target=reader_proc, args=((jqueue),))

reader_p.daemon = True

reader_p.start() ? ? # Launch the reader process

_start = time.time()

writer(count, jqueue) # Send a lot of stuff to reader_proc() (in different process)

jqueue.join() ? ? ? ? # Wait for the reader to finish

print("Sending {0} numbers to JoinableQueue() took {1} seconds".format(count,

(time.time() - _start)))

@Jonathan"總而言之,Pipe()比Queue()快三倍"

但是Pipe()不能安全地與多個生產者/消費者一起使用。

優秀的!好的答案,很高興您提供了基準!我只有兩個小問題:(1)"快幾個數量級"有點夸大其詞。差異為x3,約為一個數量級的三分之一。只是說。 ;-); (2)比較公平的比較是正在運行的N個工作程序,每個工作人員都通過點對點管道與主線程進行通信,而運行中的N個工作程序的性能都是從單個點對多點隊列中提取的。

對您的"獎金材料" ...是的。如果您是Process的子類,請將大部分run方法放在try塊中。這也是記錄異常的有用方法。復制普通異常輸出:sys.stderr.write(.join(traceback.format_exception(*(sys.exc_info()))))

通過管道將錯誤消息發送到另一個進程并在另一個進程中處理錯誤會更好嗎?

@ alexpinho98-但是您將需要一些帶外數據以及相關的信令模式,以指示您發送的不是常規數據而是錯誤數據。鑒于發起過程已經處于不可預測的狀態,這可能要問的太多了。

@邁克,只是想說你很棒。這個答案對我很有幫助。

@JJC要對自己的測驗進行測驗,3x大約是一個數量級,而不是三分之一-sqrt(10)=?3。

在multi-pipe.py中,如何知道在調用inp_p.close之前將所有項放入管道。

@ideoutrea,同意顯式比隱式好

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/455321.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/455321.shtml
英文地址,請注明出處:http://en.pswp.cn/news/455321.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

pip默認使用國內鏡像地址

很多小伙伴在ubuntu系統下,使用pip安裝會很慢 以為安裝源在國外服務器上面 今天小編就教大家配置成讓pip默認從國內源中尋找安裝包 首先CtrlAltT打開終端 進入家目錄 cd ~在家目錄中創建一個文件夾,命名為.pip mkdir .pip進入目錄,并創建一個名為pip.conf的文件 cd .pip…

“大型票務系統”和“實物電商系統”的數據庫選型

討論請移步至:http://www.zhiliaotech.com/ideajam/idea/detail/423 相關文章: 《今天你買到票了嗎?——從鐵道部12306.cn站點漫談電子商務站點的“海量事務快速處理”系統》 不能簡單套用“實物電商系統”對“大型票務系統”做需求分析 “大…

FLV文件格式(Z)(轉載)

剛才在看一些關于demux的東西,在處理flv格式的文件的時候,由于自己對flv文件的格式不了解,所以就比較云頭轉向,正好看到了一篇講述flv文件格式的文章,寫的比較明白,所以就轉過來了。O(∩_∩)O~flv頭文件比較…

mysql-5.7中的innodb_buffer_pool_prefetching(read-ahead)詳解

一、innodb的read-ahead是什么: 所謂的read-ahead就是innodb根據你現在訪問的數據,推測出你接下來可能要訪問的數據,并把它們(可能要訪問的數據)讀入 內存。 二、read-ahead是怎么做到的: 1、總的來說read-ahead利用的是程序的局部…

python compare excel_python簡單操作excle的方法

Python操作Excle文件:使用xlwt庫將數據寫入Excel表格,使用xlrd 庫從Excel讀取數據。從excle讀取數據存入數據庫1、導入模塊:import xlrd2、打開excle文件:data xlrd.open_workbook(excel.xls)3、獲取表、行/列值、行/列數、單元值…

collections系列

class Counter(dict):  Counter類繼承dict類、繼承了dict的所有功能計數器: 例:import collections obj collections.Counter(sdkasdioasdjoasjdoasd) print(obj)得:Counter({s: 5, d: 5, a: 4, o: 3, j: 2, k: 1, i: 1}) 拿到前幾位&…

Python中的虛擬環境-virtualenv

更低層次: virtualenv virtualenv 是一個創建隔絕的Python環境的 工具。virtualenv創建一個包含所有必要的可執行文件的文件夾,用來使用Python工程所需的包。 它可以獨立使用,代替Pipenv。 通過pip安裝virtualenv: $ pip install virtual…

mp4文件格式解析(一)

原文地址:mp4文件格式解析(一)作者:可下人間目前MP4的概念被炒得很火,也很亂。最開始MP4指的是音頻(MP3的升級版),即MPEG-2 AAC標準。隨后MP4概念被轉移到視頻上,對應的是…

shiro身份驗證測試

2019獨角獸企業重金招聘Python工程師標準>>> 一、登錄驗證 1、首先在shiro.ini里準備一些用戶身份/憑據,后面這里會使用數據庫代替,如: [users] [main] #realm jdbcRealmcom.learnging.system.shiro.ShiroRealm securityManager…

shell if多個條件判斷_萌新關于Excel VBA中IF條件判斷語句的一點心得體會

作者:金人瑞 《Excel VBA175例無理論純實戰教程》學員最近正在學習鄭廣學老師的VBA 175例教程,這是一篇新手向的文章,也是一個新手的總結,高手可以批評文章中的不足之處,也可以無視,VBA中的IF判斷, 判斷一般起到控制作…

Django筆記01-基礎:一個完美主義的web框架

淺談Web框架 一,什么是框架? 軟件框架就是為實現或完成某種軟件開發時,提供了一些基礎的軟件產品, 框架的功能類似于基礎設施,提供并實現最為基礎的軟件架構和體系 通常情況下我們依據框架來實現更為復雜的業務程序開發 一個字,框架就是程序的骨架 二,框架的優缺點 可重…

mysql存儲引擎的一點學習心得總結

首先我們應該了解mysql中的一個重要特性——插件式存儲引擎,從名字就能夠看出在mysql中,用戶能夠依據自己的需求隨意的選擇存儲引擎。實際上也是這樣。即使在同一個數據庫中。不同的表也能夠使用不同的存儲引擎。Mysql中支持的存儲引擎有非常多種&#x…

常見音視頻格式(轉載)

Contents 1 MPEG 系列 1.1 MPEG-1 1.2 MPEG-2 1.3 MPEG-4 1.4 MPEG-4 AVC 1.5 MPEG Audio Layer 1/2 1.6 MPEG Audio Layer 3 1.7 MPEG-2 AAC 1.8 MPEG-4 AAC 1.9 MPEG-4 aacPlus 1.10 MPEG-4 VQF 1.11 mp3PRO 1.12 MP3 Surround 2 DVD系列 2.1 Dolby Digital AC3 2.2 Dolby D…

編程語言難度排名_谷歌排名第一的編程語言,小學生拿來做答題,分分鐘鐘搞定高難度算法!...

點擊上方藍色文字關注我們吧谷歌排名第一的編程語言時什么?毫無疑問:肯定是 Python。 也難怪,作為大數據時代和人工智能時代的必備語言,Python 的優點太多了,語言簡潔、易學、開發效率高、可移植性強...... 另外&#…

poj 2484 A Funny Game

題目:http://poj.org/problem?id2484 一,題意: n個硬幣圍成一個圈,Alice與Bob輪流從圈中取硬幣。每次能夠取一枚或者連續的兩枚。 硬幣取走后留下的空位不用填補,空位相隔的兩個硬幣視為不相鄰。Alice第一個開始取。 …

58到家MySQL軍規升級版

一、基礎規范 表存儲引擎必須使用InnoDB 表字符集默認使用utf8,必要時候使用utf8mb4 解讀: (1)通用,無亂碼風險,漢字3字節,英文1字節 (2)utf8mb4是utf8的超集&#…

jsp 中包含 一個路徑為變量的文件

<head><base href"<%basePath%>"><% String fileroot"MyJsp.jsp"; %> </head><body><jsp:include page"<%fileroot %>" ></jsp:include></body>

FFMPEG中H.264的算法文檔--整理自ffmpeg論壇等

xchg_mb_border() 交換 MB 邊界的像素。閱讀代碼可知&#xff0c;交換雙方為邊界緩存 (left_border,top_borders) 與重建圖象中的相應數據。其中 xchg 參數是否為 1 決定&#xff0c;在從邊界緩存賦值到重建圖象的同時&#xff0c;是否保存重建圖象的數據到邊界緩存。 此函數僅…

python局部靜態變量_全局變量、局部變量和靜態變量

全局變量和局部變量在寫代碼時需要區分清楚&#xff0c;不然會出大問題。不同語言定義不同范圍的變量的寫法有很大的區別。那么靜態變量是在什么場景下用到呢&#xff1f;我們來假設這樣一個場景&#xff1a;在函數內部定義的變量&#xff0c;當程序執行到它的定義處時&#xf…

【轉載】fullpage.js學習

參考網址&#xff1a;http://www.dowebok.com/77.html 上面有詳細介紹及案例展示&#xff0c;很不錯哦&#xff0c;可以先去看看demo 一、簡介 fullPage.js 是一個基于jQuery的插件&#xff0c;它能夠很方便、很輕松的制作出全屏網站&#xff0c;主要功能有&#xff1a; 1.支持…