首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >threading.Condition与threading.Event的区别

threading.Condition与threading.Event的区别
EN

Stack Overflow用户
提问于 2022-06-26 11:27:27
回答 1查看 120关注 0票数 1

现有的threading.Condition和threading.Event在互联网上的应用都是为了解决生产者的消费问题。但是这可以用他们中的任何一个来完成。我发现的条件的唯一优点是-它支持两种类型的通知函数(通知和notifyAll)。

在这里,我已经很容易地复制了一个现有的条件到事件的例子。条件示例取自这里

使用条件的示例:

代码语言:javascript
复制
def consumer(cv):
    logging.debug('Consumer thread started ...')
    with cv:
        logging.debug('Consumer waiting ...')
        cv.wait()
        logging.debug('Consumer consumed the resource')

def producer(cv):
    logging.debug('Producer thread started ...')
    with cv:
        logging.debug('Making resource available')
        logging.debug('Notifying to all consumers')
        cv.notifyAll()

if __name__ == '__main__':
    condition = threading.Condition()
    cs1 = threading.Thread(name='consumer1', target=consumer, args=(condition,))
    cs2 = threading.Thread(name='consumer2', target=consumer, args=(condition,))
    pd = threading.Thread(name='producer', target=producer, args=(condition,))

    cs1.start()
    time.sleep(2)
    cs2.start()
    time.sleep(2)
    pd.start()

使用事件的示例:

代码语言:javascript
复制
def consumer(ev):
    logging.debug('Consumer thread started ...')
    logging.debug('Consumer waiting ...')
    ev.wait()
    logging.debug('Consumer consumed the resource')

def producer(ev):
    logging.debug('Producer thread started ...')
    logging.debug('Making resource available')
    logging.debug('Notifying to all consumers')
    ev.set()

if __name__ == '__main__':
    event = threading.Event()
    cs1 = threading.Thread(name='consumer1', target=consumer, args=(event,))
    cs2 = threading.Thread(name='consumer2', target=consumer, args=(event,))
    pd = threading.Thread(name='producer', target=producer, args=(event,))

    cs1.start()
    time.sleep(2)
    cs2.start()
    time.sleep(2)
    pd.start()

输出:

代码语言:javascript
复制
(consumer1) Consumer thread started ...
(consumer1) Consumer waiting ...
(consumer2) Consumer thread started ...
(consumer2) Consumer waiting ...
(producer ) Producer thread started ...
(producer ) Making resource available
(producer ) Notifying to all consumers
(consumer1) Consumer consumed the resource
(consumer2) Consumer consumed the resource

有人能给出一个可以使用条件而不是事件的例子吗?

EN

回答 1

Stack Overflow用户

发布于 2022-06-26 13:59:17

Event有一个状态:您可以调用e.is_set()来了解eset()还是clear()ed。

Condition没有状态。如果当其他线程在c.notify()中等待时,某个线程碰巧调用了c.wait()c.notify_all(),那么其他线程中的一个或多个将被唤醒。但是,如果通知是在没有其他线程等待的时候发出的,那么c.notify()c.notify_all()绝对不会做任何事情。

简而言之:Event是一种完整的通信机制,可以用来将信息从一个线程传输到另一个线程。但是,Condition本身不能可靠地用于通信。它必须被纳入一个更大的计划。

国际海事组织:这两个班的名字都不太好。Event的一个更好的名称是Bit,因为它存储了一点信息。

Condition的一个更好的名称是Event。通知一个条件是一个“事件”,它是这个词的真正意义。如果你碰巧看到它发生的时候,那么你就学到了一些东西。但如果你没有碰巧在看,那你就完全错过了。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72761157

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档