class WorkerThread(threading.Thread):
"""Background thread connected to the requests/results queues.
A worker thread sits in the background and picks up work requests from
one queue and puts the results in another until it is dismissed.
"""
def __init__(self, requests_queue, results_queue, poll_timeout=5, **kwds):
"""Set up thread in daemonic mode and start it immediatedly.
``requests_queue`` and ``results_queue`` are instances of
``Queue.Queue`` passed by the ``ThreadPool`` class when it creates a
new worker thread.
"""
threading.Thread.__init__(self, **kwds)
self.setDaemon(1)#
self._requests_queue = requests_queue#任务队列
self._results_queue = results_queue#任务结果队列
self._poll_timeout = poll_timeout#run函数中从任务队列中get任务时的超时时间,如果超时则继续while(true);
self._dismissed = threading.Event()#线程事件,如果set线程事件则run会执行break,直接退出工作线程;
self.start()
def run(self):
"""Repeatedly process the job queue until told to exit."""
while True:
if self._dismissed.isSet():#如果设置了self._dismissed则退出工作线程
# we are dismissed, break out of loop
break
# get next work request. If we don't get a new request from the
# queue after self._poll_timout seconds, we jump to the start of
# the while loop again, to give the thread a chance to exit.
try:
request = self._requests_queue.get(True, self._poll_timeout)
except Queue.Empty:#尝从任务 队列self._requests_queue 中get任务,如果队列为空,则continue
continue
else:
if self._dismissed.isSet():#检测此工作线程事件是否被set,如果被设置,意味着要结束此工作线程,那么就需要将取到的任务返回到任务队列中,并且退出线程
# we are dismissed, put back request in queue and exit loop
self._requests_queue.put(request)
break
try:
"""
self._dismissed.set()