利用condition实现等待唤醒操作和生产消费的同步处理;
import threading,time,sched
class Message:
def __init__(self,condition):
self._title = None;
self._content = None;
self._flag = True;
self._condition = condition;
def set_info(self,title,content):
self._condition.acquire();
if self._flag == False:
self._condition.wait();
self._title = title;
time.sleep(1);
self._content = content;
print("{}-title = {},content = {}".format(threading.current_thread().name,self._title,self._content));
self._flag = False;
self._condition.notify();
self._condition.release();
def __str__(self):
self._condition.acquire();
if self._flag == True:
self._condition.wait();
try:
time.sleep(0.8);
return "{}-title = {},content = {}".format(threading.current_thread().name,self._title,self._content);
finally:
self._flag = True;
self._condition.notify();
self._condition.release();
# 生产者处理函数
def producer_handle(message):
for num in range(50):
if num % 2 == 0:
message.set_info("奥特曼","奥特曼打怪兽");
else:
message.set_info("黑猫警长","黑猫警长抓老鼠");
# 消费者处理函数
def consumer_handle(message):
for num in range(50):
print(message);
def main():
# 实例化条件锁
condition = threading.Condition();
# 公共保存的数据对象
message = Message(condition);
prodecer_thread = threading.Thread(target=producer_handle,name = "生产者线程",args=(message,));
consumer_thread = threading.Thread(target=consumer_handle,name = "消费者线程",args=(message,));
prodecer_thread.start();
consumer_thread.start();
if __name__ == '__main__':
main();
使用这个会有一个问题,生产一个消费一个,那么如果没有消费完的话就不会继续生产,这样会出现资源的浪费,如果你使用过mq的话这个就很好理解了,使用队列来解决这种问题;
python中提供了queue模块来实现
1.queue.Queue 先进先出 同步队列
2.queue.LifoQueue 后进先出 同步队列
3.queue.PriorityQueue 优先级队列
此时性能不会有问题,也不需要使用同步机制了;
import threading,time,queue
class Message:
def __init__(self):
self._title = None;
self._content = None;
def set_info(self,title,content):
self._title = title;
self._content = content;
time.sleep(0.1);
print("{}-title = {},content = {}".format(threading.current_thread().name,self._title,self._content));
def __str__(self):
time.sleep(0.8);
return "{}-title = {},content = {}".format(threading.current_thread().name,self._title,self._content);
# 生产者处理函数
def producer_handle(work_queue):
for num in range(50):
message = Message();
if num % 2 == 0:
message.set_info("奥特曼","奥特曼打怪兽:{}".format(num));
else:
message.set_info("黑猫警长","黑猫警长抓老鼠:{}".format(num));
work_queue.put(message);
# 消费者处理函数
def consumer_handle(work_queue):
for num in range(50):
print(work_queue.get());
def main():
# 创建5个队列
work_queue = queue.Queue(5);
prodecer_thread = threading.Thread(target=producer_handle,name = "生产者线程",args=(work_queue,));
consumer_thread = threading.Thread(target=consumer_handle,name = "消费者线程",args=(work_queue,));
prodecer_thread.start();
consumer_thread.start();
if __name__ == '__main__':
main();