这个模型使用python来实现相比POSIX来做简单太多太多了,轮子python都可以写好了直接调用即可,队列就已经封装好了对共享数据的安全访问。在POSIX多线程中考虑Mutex和条件变量是一个重点。这是我以前用POSIX pthread函数实现的一个生产者和消费者模型:
-
http://blog.itpub.net/7728585/viewspace-2139638/
(LINUX 线程同步) 互斥量、条件变量以及生产者消费者问题
一、实现方式
下面是Python实现的方法,实际上就是使用队列作为共享数据的中间价这是模块封装好的,不需要在使用Mutex保护线程之间共享数据访问的
安全性。附带队列的测试代码,代码简单如下:
点击(此处)折叠或打开
-
import threading
-
import time
-
import queue
-
from global_par import global_par
-
#queue is especially useful in threaded programming when information must be exchanged safely between multiple threads.
-
-
def Prod(global_data):
-
"""生产者线程"""
-
i = 1
-
qfifo = global_data.get_global_pars("CusQue")
-
while 1:
-
qfifo.put(i)
-
print("生产产品: {} ".format(i))
-
i +=1;
-
return 0
-
-
def Cust(global_data,detail):
-
"""消费者线程"""
-
qfifo = global_data.get_global_pars("CusQue")
-
while 1:
-
print("{}:消费产品:{}".format(detail,qfifo.get()))
-
time.sleep(1)
-
return 0
-
-
def main():
-
pthread_list = []
-
global_data = global_par()
-
qfifo = queue.Queue(maxsize=10)
-
global_data.set_global_pars("CusQue",qfifo)
-
-
##建立1个生产者线程
-
thread_pro = threading.Thread(target=Prod,args=(global_data,))
-
pthread_list.append(thread_pro)
-
-
##建立10个消费者线程
-
for i in range(10):
-
thread_cus = threading.Thread(target=Cust, args=(global_data, "消费线程{}".format(i+1),))
-
pthread_list.append(thread_cus)
-
-
for i in pthread_list:
-
i.start()
-
-
for i in pthread_list:
-
i.join
-
-
return 0
-
-
if __name__ == '__main__':
- main()
二、队列测试代码
点击(此处)折叠或打开
-
import threading
-
import queue
-
#http://www.cnblogs.com/alex3714/articles/5230609.html
-
-
def my_format(x, y):
-
"""par one: what des your print
-
par two: value
-
"""
-
x = "-->" + x + " {}"
-
print(x.format(y))
-
return
-
-
qfifo = queue.Queue(maxsize=2) ##先进先出队列 如果达到最大值默认Queue.put()会堵塞 如果为空默认Queue.get()会堵塞
-
qlifo = queue.LifoQueue(maxsize=2) ##后入先出队列 如果达到最大值默认Queue.put()会堵塞 如果为空默认Queue.get()会堵塞
-
qpri = queue.PriorityQueue(maxsize=2) ##根据优先级判断顺序小的为优先级高 如果达到最大值默认Queue.put()会堵塞 如果为空默认Queue.get()会堵塞
-
-
##part0:在队列增加元素Queue.put(item, block=True, timeout=None) 可以设置是否堵塞
-
my_format("##part0:在队列增加元素Queue.put(item, block=True, timeout=None):","")
-
qfifo.put(1)
-
qfifo.put(2)
-
##part1:队列满了会报queue.Full异常
-
try:
-
qfifo.put(2,timeout=1)
-
except queue.Full as e:
-
my_format("##part1:队列满了如果不堵塞会报queue.Full异常", "")
-
-
##part2:出队列Queue.get(block=True, timeout=None) 可以设置是否堵塞
-
-
my_format("##part2:出队列Queue.get(block=True, timeout=None) 可以设置是否堵塞:","")
-
qfifo.get()
-
qfifo.get()
-
-
##part3:队列空如果不堵塞会报异常queue.Empty
-
try:
-
qfifo.get(timeout=1)
-
except queue.Empty as e:
-
my_format("##part3:队列空如果不堵塞会报异常queue.Empty", "")
-
-
-
##part4:返回队列的大小Queue.qsize()
-
my_format("##part0:返回队列的大小Queue.qsize():",qfifo.qsize())
-
-
##part5:返回是否为空的bool值Queue.empty()
-
my_format("##part1:返回是否为空的bool值Queue.empty():",qfifo.empty())
-
-
##part6:返回是否满的bool值Queue.full()
-
- my_format("##part1:返回是否为空的bool值Queue.full():",qfifo.full())
作者微信: