寫這篇博客的原因是因爲很多生產者消費者都在兩個class裏面,這會導致在集成的時候不是那麼方便
import multiprocessing
import threading
from multiprocessing import Process, Queue
import time, random, os
listcase1 = ["route_{}".format(i) for i in range(20)]
class Consumer_Producer():
def __init__(self, queue):
self.queue = queue
#生產者,從list_case1中得到數據,你也可以隨機生成再put進去,這樣程序永遠不會停止
def producer(self):
while len(listcase1)>0:
self.a = listcase1.pop()
self.queue.put(self.a)
print('add {}'.format(self.a))
time.sleep(random.random())
#消費者,從self.queue中獲取數據
def consumer(self):
while True:
get_case = self.queue.get()
#self.cslist.append(get_case)
print('lose {}'.format(get_case))
time.sleep(2)
def run(self):
p1 = threading.Thread(target=self.producer)
c1 = threading.Thread(target=self.consumer)
p1.start()
c1.start()
p1.join()
c1.join()
queue = Queue(5) #設置隊列裏面最多五個
run_table = Consumer_Producer(queue) #將所有
run_table.run() #因爲沒有繼承threading.Thread,所以需要手動調用run
case因爲沒有問題,如果有什麼問題請聯繫我
運行結果:
$ python test1.py
add route_19
lose route_19
add route_18
add route_17
add route_16
lose route_18
add route_15
add route_14
lose route_17
add route_13
add route_12
lose route_16
add route_11