- 论坛徽章:
- 0
|
周末阅读《Python标准库》一书的threading部分,以我vxworks为主的c语言开发经验,对标准库中的task同步互斥理解有些疑问,不得要领。
在此把我的疑惑讲出来,求得各位有何见解和真知。
案例代码:
1.1同步线程 使用 condition- logging.basicConfig(
- level=logging.DEBUG,
- format='%(asctime)s (%(threadName)-2s) %(message)s',
- )
- def consumer(cond):
- """wait for the condition and use the resource"""
- logging.debug('Starting consumer thread')
- t = threading.currentThread()
- [color=Red]with cond:[/color]
- [color=Red]cond.wait()[/color]
- logging.debug('Resource is available to consumer')
- def producer(cond):
- """set up the resource to be used by the consumer"""
- logging.debug('Starting producer thread')
- [color=Red]with cond:[/color]
- logging.debug('Making resource available')
- [color=Red]cond.notifyAll()[/color]
- condition = threading.Condition()
- c1 = threading.Thread(name='c1', target=consumer,
- args=(condition,))
- c2 = threading.Thread(name='c2', target=consumer,
- args=(condition,))
- p = threading.Thread(name='p', target=producer,
- args=(condition,))
- c1.start()
- time.sleep(2)
- c2.start()
- time.sleep(2)
- p.start()
复制代码 1.2线程间传递信号 使用event- logging.basicConfig(level=logging.DEBUG,
- format='(%(threadName)-10s) %(message)s',
- )
-
- def wait_for_event(e):
- """Wait for the event to be set before doing anything"""
- logging.debug('wait_for_event starting')
- event_is_set = [color=Red]e.wait()[/color]
- logging.debug('event set: %s', event_is_set)
- def wait_for_event_timeout(e, t):
- """Wait t seconds and then timeout"""
- while not e.isSet():
- logging.debug('wait_for_event_timeout starting')
- event_is_set = e.wait(t)
- logging.debug('event set: %s', event_is_set)
- if event_is_set:
- logging.debug('processing event')
- else:
- logging.debug('doing other work')
- e = threading.Event()
- t1 = threading.Thread(name='block',
- target=wait_for_event,
- args=(e,))
- t1.start()
- t2 = threading.Thread(name='nonblock',
- target=wait_for_event_timeout,
- args=(e, 2))
- t2.start()
- logging.debug('Waiting before calling Event.set()')
- time.sleep(3)
- [color=Red]e.set()[/color]
- logging.debug('Event is set')
复制代码 疑问:
我初略理解为condition就是lock+event。
所以同步线程采用的代码结构是- with cond:
- cond.wait()
- 与
- with cond:
- cond.notifyAll()
复制代码 而线程间传递信号的代码结构是我觉得cond用法中的lock是重复的,反正就需要cond.wait了(忽略e.set()和cond.notifyAll()的细微差别)。我还要with cond(请求锁)干什么呢。
就像vxworks中semTake()和semGive()一样。这个cond.wait()天生就是包含了阻塞等待的意思。
|
|