1. 程式人生 > >python 實現多個線程間消息隊列傳遞,一個簡單的列子

python 實現多個線程間消息隊列傳遞,一個簡單的列子

一致性 不同 lee mode any sum ase utf ()


#-*-coding:utf8-*-
"""
Producer and consumer models:
1. There are many producers and consumers at the same time, but they complement each other.


Implemented by message queuing to achieve at the same time production and consumpion processing.

"""

import threading
import time
import Queue
import random


lock = threading.RLock()
q = Queue.Queue()
count = 0

#第一個線程,用於入隊列
class Mythread_1(threading.Thread):

def __init__(self,Producername):
threading.Thread.__init__(self)
self.Producername = Producername



def Producer(self,name):

name = self.Producername

for i in range(20):
       #進隊列
q.put(i)
print ‘\033[34;1mProducer %s,now produce %s to the consumers...\033[0m‘ %(name,i)
       #通過控制休眠,來觀察入列情況 
time.sleep(random.randrange(2))
print ‘Producer comes here‘


def run(self):
     #lock.acquire()
self.Producer(self.Producername)
     #lock.release()

#第二個線程用於出隊列
class Mythread_2(threading.Thread):
def __init__(self,Consumername):
threading.Thread.__init__(self)
self.Consumername = Consumername

def Consumer(self,name):

name = self.Consumername
global count

while count < 20:
#lock.acquire()
       #出隊列
data = q.get()

print ‘\033[35;1mConsumer %s,now get the %s from the producers...\033[0m‘ %(name,data)
count += 1
       #用來控制休眠之間,以便來觀察出隊列情況
time.sleep(random.randrange(2))
print ‘Consumer comes here‘


def run(self):
     #lock.acquire()
self.Consumer(self.Consumername)
  #lock.release()


t1 = Mythread_1("longyongzhen")

t2 = Mythread_2("weichunyuan")

‘‘‘
def Producer(name):
for i in range(20):
q.put(i)
print ‘\033[34;1mProducer %s,now produce %s to the consumers...\033[0m‘ %(name,i)
time.sleep(random.randrange(3))

def Consumer(name):
count = 0
while count < 20:
data = q.get()
print ‘\033[35;1mConsumer %s,now get the %s from the producers...\033[0m‘ %(name,data)
count += 1
time.sleep(random.randrange(2))

p = threading.Thread(target=Producer,args=("longyongzhen",))
c = threading.Thread(target=Consumer,args=("weichunyuan",))



p.start()
c.start()
‘‘‘
t1.start()
t2.start()
-----------------------------------
多次實驗可以得出的結果是:
1、python的消息隊列只要定義一個隊列,如上面的q,則不同線程之間隊列的入列和出列,只要調用q,則保證了隊列的一致性,入列出列是對應的。
2、如果要對線程進行加鎖,則隊列的出列,要等所有都入列了之後才會釋放資源,這種方式資源利用率太低。



python 實現多個線程間消息隊列傳遞,一個簡單的列子