ThreadPool是线程池类,但原来作者只提供了任务函数的接口,没有提供任务类的接口,类似threading.Thread接口函数。在本文中修改makeRequests函数提供类似接口。(红色字体),关于ThreadPool代码不在本文介绍,请参考http://www.cnblogs.com/tracylining/p/3471594.html
<span style="font-size:14px;">import sys
import threading
import Queue
import traceback
# exceptions
class NoResultsPending(Exception):
"""All work requests have been processed."""
pass
class NoWorkersAvailable(Exception):
"""No worker threads available to process remaining requests."""
pass
# internal module helper functions
def _handle_thread_exception(request, exc_info):
"""Default exception handler callback function.
This just prints the exception info via ``traceback.print_exception``.
"""
traceback.print_exception(*exc_info)
# utility functions
def makeRequests(callable_, args_list=None, callback=None,
exc_callback=_handle_thread_exception):
"""Create several work requests for same callable with different arguments.
Convenience function for creating several work requests for the same
callable where each invocation of the callable receives different values
for its arguments.
``args_list`` contains the parameters for each invocation of callable.
Each item in ``args_list`` should be either a 2-item tuple of the list of
positional arguments and a dictionary of keyword arguments or a single,
non-tuple argument.
See docstring for ``WorkRequest`` for info on ``callback`` and
``exc_callback``.
"""
<span style="color:#FF0000;"> requests = []
if args_list==None:
requests.append(WorkRequest(callable_, None, None, callback=callback,
exc_callback=exc_callback))
else:
for item in args_list:
if isinstance(item, tuple):
requests.append(
WorkRequest(callable_, item[0], item[1], callback=callback,
exc_callback=exc_callback)
)
else:
requests.append(
WorkRequest(callable_, [item], None, callback=callback,
exc_callback=exc_callback)
)
return requests</span>
# classes
class WorkerThread(threading.Thread):
"""Background thread connected to the requests/results queues