Condition同步处理

# 使用Condition 实现生产者与消费者模型
'''
def __init__(self,lock=None)
def acquire(self,blocking = True ,timeout = -1)
def wait(self,timeout = None)
def notify(self,n=1) 唤醒一个等待线程对象
def notify_all(self) 唤醒所有等待的线程
'''
import threading
import time


class msg:
    def __init__(self, condition):
        self.__title = None
        self.__content = None
        self.__condition = condition  # 实例化锁
        self.__flag = True  # 用于进行生产者和消费者线程的切换 其值为true 时可以生产 ,不能消费 为false可以消费 ,不能生产

    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('%s title =%s content = %s' % (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 '%s title =%s content = %s' % (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('chenxianq','测试工程师')
            else:
                message.set_info('tencent','www.tencent.com')

def consumer_handle(message):
    for num in range(50):
        print(message)

def main():
    condition =threading.Condition()   # 实例化条件锁
    message = msg(condition)
    producter_thred = threading.Thread(target=producer_handle,name='生产线程',args=(message,))
    consumer_thred = threading.Thread(target=consumer_handle,name='消费线程',args=(message,))

    producter_thred.start()
    consumer_thred.start()

if __name__ == '__main__':
    main()
posted @ 2022-04-11 23:56  饭兜  阅读(20)  评论(0编辑  收藏  举报