@@ -129,3 +129,69 @@ $ python temp.py
129129请注意,首先创建并初始化 ` fibonacci_task` 线程,然后它们进入等待状态。 同时,创建 ` queue_task` 并填充 ` shared_queue` 。 最后,` queue_task` 通知 ` fibonacci_task` 线程它们可以执行它们的任务。
130130
131131请注意,` fibonacci_task` 线程的执行不遵循顺序逻辑,每次执行的顺序可能不同。 这就是使用线程的一个特点:** 非确定性** (non-determinism)。
132+
133+ # # 完整例子
134+
135+ 译者注:
136+
137+ ` ` ` python
138+
139+ # coding: utf-8
140+
141+ import logging, threading
142+
143+ from queue import Queue
144+
145+ logger = logging.getLogger ()
146+ logger.setLevel(logging.DEBUG)
147+ formatter = logging.Formatter(' %(asctime)s - %(message)s' )
148+
149+ ch = logging.StreamHandler ()
150+ ch.setLevel(logging.DEBUG)
151+ ch.setFormatter(formatter)
152+ logger.addHandler(ch)
153+
154+ fibo_dict ={}
155+ shared_queue = Queue ()
156+ input_list = [3, 10, 5, 7]
157+
158+ queue_condition = threading.Condition ()
159+
160+ def fibonacci_task(condition):
161+ with condition:
162+ while shared_queue.empty ():
163+ logger.info(" [%s] - waiting for elements in queue.." % threading.current_thread ().name)
164+ condition.wait ()
165+ else:
166+ value = shared_queue.get ()
167+ a, b = 0, 1
168+ for item in range(value):
169+ a, b = b, a + b
170+ fibo_dict[value] = a
171+ shared_queue.task_done ()
172+ logger.debug(" [%s] fibonacci of key [%d] with result [%d]" % (threading.current_thread().name, value, fibo_dict[value]))
173+
174+ def queue_task(condition):
175+ logging.debug(' Starting queue_task...' )
176+ with condition:
177+ for item in input_list:
178+ shared_queue.put(item)
179+ logging.debug(" Notifying fibonacci_task threadsthat the queue is ready to consume.." )
180+ condition.notify_all ()
181+
182+
183+
184+
185+ if __name__ == " __main__" :
186+ threads = [
187+ threading.Thread(daemon=True, target=fibonacci_task,args=(queue_condition,))
188+ for i in range(4)
189+ ]
190+
191+ [thread.start() for thread in threads]
192+
193+ prod = threading.Thread(name=' queue_task_thread' , daemon=True, target=queue_task, args=(queue_condition,))
194+ prod.start ()
195+
196+ [thread.join() for thread in threads]
197+ ` ` `
0 commit comments