python多线程监听变量

python多线程监听变量

python多线程监听变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import threading
import time
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-9s) %(message)s',)

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

输出:

1
2
3
4
5
6
7
8
9
(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

如果要监听变量:

1
2
3
4
5
6
7
8
9
10
# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()

本文网址: https://pylist.com/topic/169.html 转摘请注明来源

Suggested Topics

SAE+python+Tornado+pyTenjin 的完整示例

python 简单易懂,Tornado 高效易学,pyTenjin 轻巧快速,SAE 安全稳定使用门槛低。现在把他们结合在一起做了一个可运行在SAE 上的完整示例。...

python 使用 magic 从文件内容判断文件类型

使用 python-magic 库可以轻松识别文件的类型,python-magic是libmagic文件类型识别库的python接口。libmagic通过根据预定义的文件类型列表检查它们的头文件来识别文件类型。 ...

Leave a Comment