Pythonプロデューサーとコンシューマーの条件の同期処理とキュー処理

条件を使用して、ウェイクアップ操作と生産および消費を待機する同期処理を実現します。

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();

これを使うと問題があります、1つは生産されてもう1つは消費されます、そして消費が終了しないと生産は継続されないので、リソースの浪費になります、mqを使用した場合、これはよく理解されています、キューを使用してこの質問を解決
します
。Pythonには、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();

おすすめ

転載: blog.csdn.net/weixin_44887276/article/details/114880577