Python程序間通訊Queue例項解析

2022-10-04 20:24:44 字數 2946 閱讀 8173

1.queue使用方法:

2.queue使用例項:

來,上**:

#!/usr/bin/env python3

import time

from multiprocessing import process,queue

q = queue() #建立列隊,不傳數字表示列隊不限數量

for i in range(11):

q.put(i)

def a():

while 1:

try:

num = q.get_nowait()

print('我是程序a,取出數字:%d'%num)

time.sleep(1)

except :

break

def b():

while 1:

try:

num = q.get_nowait()

print('我是程序b,取出數字:%d'%num)

time.sleep(1)

except :

break

p1 = process(target = a)

p2 = process(target = b)

p1.start()

p2.start()

此程式是在佇列中加入10個數字,然後用2個程序來取出。

執行結果:

我是程序a,取出數字:0

我是程序b,取出數字:1

我是程序a,取出數字:2

我是程序b,取出數字:3

我是程序a,取出數字:4

我是程序b,取出數字:5

我是程序b,取出數字:6

我是程序a,取出數字:7

我是程序b,取出數字:8

我是程序a,取出數字:9

我是程序b,取出數字:10

3.使用程序池pool時,queue會出錯,需要使用manager.queue:

上**#!/usr/bin/env python3

import time

from multiprocessing import pool,manager,queue

q = manager().queue()

for i in range(11):

q.put(i)

def a(i):

num = q.get_nowait()

print('我是程序%d,取出數字:%d'%(i,num))

time.sleep(1)

pool = pool(3)

for i in range(10):

pool.apply_async(a,(i,))

pool.close()

pool.join()

執行結果:

我是程序1,取出數字:0

我是程序0,取出www.cppcns.com數字:1

我是程序2,取出數字:2

我是程序4,取出數字:3

我是程序3,取出數字:4

我是程序5,取出數字:5

我是程序6,取出數字:6

我是程序7,取出數字:7

我是程序8,取出數字:8

我是程序9,取出數字:9

當把manager().queue()直接換成queue(),可能會出現資源混亂,缺少程序。

4.主程序定義了乙個queue型別的變數,並作為process的args引數傳給子程序processa和processb,兩個程序乙個向佇列中寫資料,乙個讀資料。

import time

from multiprocessin程式設計客棧g import process,queue

msg_queue = queue(5)

def starta(msgqueue):

while true:

if msgqueue.empty() > 0:

print 'queue is empty %d' % (msgqueue.qsize())

else:

msg = msgqueue.get()

print 'get msg %s' % (msg,)

time.sleep(1)

def startb(msgqueue):

while true:

msgqueue.put('hello world')

print 'put hello world queue size is %d' % (msgqueue.qsize(),)

time.sleep(3)

if __name__ == '__main__':

processa = process(target=starta,args=(msg_queue,))

processb = process(target=startb,args=(msg_queue,))

processa.start()

print 'processa start..'

processb.start()

print 'processb start..'

其列印的結果如下:

c:\python27\python.exe e:/outofmemory/test/queuetest/queuetest.py

processa start..

processb start..

queue is empty 0

put hello world queue size is 1

get msg hello world

queue is empty 0

queue is empty 0

put hello world queue size is 1

get 程式設計客棧msg hello world

queue is empty 0

queue is empty 0

put hello world queue size is 1

總結

Python多程序 程序間通訊

1.使用multiprocessing模組建立的程序之間的通訊 coding utf 8 queue類常用屬性和方法 init self,maxsize 1 qsize full empty put obj,block true,timeout none put nowait obj get blo...

Python基礎 程序間通訊

程序間通訊 windows下程序間通訊有很多種,例如 訊息佇列 共享記憶體 管道等等。python的multiprocessing模組包裝了底層的機制,提供了queue pipes等多種方式來交換資料。multiprocessing.pipe 即管道模式,呼叫pipe 返回管道的兩端的connect...

python中程序間通訊

程序間通訊 磁碟互動 速度慢 不安全 socket 本地套接字 管道 訊息列隊 共享記憶體 訊號 訊號量 套接字 管道通訊 pipe 在記憶體中開闢一塊空間,對多個程序可見,通過管道 多個程序進行通訊 multiprocessing pipe fd1,fd2 pipe duplex true 功能 ...