threadpool.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. # -*- coding: UTF-8 -*-
  2. """Easy to use object-oriented thread pool framework.
  3. A thread pool is an object that maintains a pool of worker threads to perform
  4. time consuming operations in parallel. It assigns jobs to the threads
  5. by putting them in a work request queue, where they are picked up by the
  6. next available thread. This then performs the requested operation in the
  7. background and puts the results in another queue.
  8. The thread pool object can then collect the results from all threads from
  9. this queue as soon as they become available or after all threads have
  10. finished their work. It's also possible, to define callbacks to handle
  11. each result as it comes in.
  12. The basic concept and some code was taken from the book "Python in a Nutshell,
  13. 2nd edition" by Alex Martelli, O'Reilly 2006, ISBN 0-596-10046-9, from section
  14. 14.5 "Threaded Program Architecture". I wrapped the main program logic in the
  15. ThreadPool class, added the WorkRequest class and the callback system and
  16. tweaked the code here and there. Kudos also to Florent Aide for the exception
  17. handling mechanism.
  18. Basic usage::
  19. >>> pool = ThreadPool(poolsize)
  20. >>> requests = makeRequests(some_callable, list_of_args, callback)
  21. >>> [pool.putRequest(req) for req in requests]
  22. >>> pool.wait()
  23. See the end of the module code for a brief, annotated usage example.
  24. Website : http://chrisarndt.de/projects/threadpool/
  25. """
  26. __docformat__ = "restructuredtext en"
  27. __all__ = [
  28. 'makeRequests',
  29. 'NoResultsPending',
  30. 'NoWorkersAvailable',
  31. 'ThreadPool',
  32. 'WorkRequest',
  33. 'WorkerThread'
  34. ]
  35. __author__ = "Christopher Arndt"
  36. __version__ = '1.3.2'
  37. __license__ = "MIT license"
  38. # standard library modules
  39. import sys
  40. import threading
  41. import traceback
  42. try:
  43. import Queue # Python 2
  44. except ImportError:
  45. import queue as Queue # Python 3
  46. # exceptions
  47. class NoResultsPending(Exception):
  48. """All work requests have been processed."""
  49. pass
  50. class NoWorkersAvailable(Exception):
  51. """No worker threads available to process remaining requests."""
  52. pass
  53. # internal module helper functions
  54. def _handle_thread_exception(request, exc_info):
  55. """Default exception handler callback function.
  56. This just prints the exception info via ``traceback.print_exception``.
  57. """
  58. traceback.print_exception(*exc_info)
  59. # utility functions
  60. def makeRequests(callable_, args_list, callback=None,
  61. exc_callback=_handle_thread_exception):
  62. """Create several work requests for same callable with different arguments.
  63. Convenience function for creating several work requests for the same
  64. callable where each invocation of the callable receives different values
  65. for its arguments.
  66. ``args_list`` contains the parameters for each invocation of callable.
  67. Each item in ``args_list`` should be either a 2-item tuple of the list of
  68. positional arguments and a dictionary of keyword arguments or a single,
  69. non-tuple argument.
  70. See docstring for ``WorkRequest`` for info on ``callback`` and
  71. ``exc_callback``.
  72. """
  73. requests = []
  74. for item in args_list:
  75. if isinstance(item, tuple):
  76. requests.append(
  77. WorkRequest(callable_, item[0], item[1], callback=callback,
  78. exc_callback=exc_callback)
  79. )
  80. else:
  81. requests.append(
  82. WorkRequest(callable_, [item], None, callback=callback,
  83. exc_callback=exc_callback)
  84. )
  85. return requests
  86. # classes
  87. class WorkerThread(threading.Thread):
  88. """Background thread connected to the requests/results queues.
  89. A worker thread sits in the background and picks up work requests from
  90. one queue and puts the results in another until it is dismissed.
  91. """
  92. def __init__(self, requests_queue, results_queue, poll_timeout=5, **kwds):
  93. """Set up thread in daemonic mode and start it immediatedly.
  94. ``requests_queue`` and ``results_queue`` are instances of
  95. ``Queue.Queue`` passed by the ``ThreadPool`` class when it creates a
  96. new worker thread.
  97. """
  98. threading.Thread.__init__(self, **kwds)
  99. self.setDaemon(1)
  100. self._requests_queue = requests_queue
  101. self._results_queue = results_queue
  102. self._poll_timeout = poll_timeout
  103. self._dismissed = threading.Event()
  104. self.start()
  105. def run(self):
  106. """Repeatedly process the job queue until told to exit."""
  107. while True:
  108. if self._dismissed.isSet():
  109. # we are dismissed, break out of loop
  110. break
  111. # get next work request. If we don't get a new request from the
  112. # queue after self._poll_timout seconds, we jump to the start of
  113. # the while loop again, to give the thread a chance to exit.
  114. try:
  115. request = self._requests_queue.get(True, self._poll_timeout)
  116. #except Queue.Empty:
  117. except:
  118. continue
  119. else:
  120. if self._dismissed.isSet():
  121. # we are dismissed, put back request in queue and exit loop
  122. self._requests_queue.put(request)
  123. break
  124. try:
  125. result = request.callable(*request.args, **request.kwds)
  126. self._results_queue.put((request, result))
  127. except:
  128. request.exception = True
  129. self._results_queue.put((request, sys.exc_info()))
  130. def dismiss(self):
  131. """Sets a flag to tell the thread to exit when done with current job.
  132. """
  133. self._dismissed.set()
  134. class WorkRequest:
  135. """A request to execute a callable for putting in the request queue later.
  136. See the module function ``makeRequests`` for the common case
  137. where you want to build several ``WorkRequest`` objects for the same
  138. callable but with different arguments for each call.
  139. """
  140. def __init__(self, callable_, args=None, kwds=None, requestID=None,
  141. callback=None, exc_callback=_handle_thread_exception):
  142. """Create a work request for a callable and attach callbacks.
  143. A work request consists of the a callable to be executed by a
  144. worker thread, a list of positional arguments, a dictionary
  145. of keyword arguments.
  146. A ``callback`` function can be specified, that is called when the
  147. results of the request are picked up from the result queue. It must
  148. accept two anonymous arguments, the ``WorkRequest`` object and the
  149. results of the callable, in that order. If you want to pass additional
  150. information to the callback, just stick it on the request object.
  151. You can also give custom callback for when an exception occurs with
  152. the ``exc_callback`` keyword parameter. It should also accept two
  153. anonymous arguments, the ``WorkRequest`` and a tuple with the exception
  154. details as returned by ``sys.exc_info()``. The default implementation
  155. of this callback just prints the exception info via
  156. ``traceback.print_exception``. If you want no exception handler
  157. callback, just pass in ``None``.
  158. ``requestID``, if given, must be hashable since it is used by
  159. ``ThreadPool`` object to store the results of that work request in a
  160. dictionary. It defaults to the return value of ``id(self)``.
  161. """
  162. if requestID is None:
  163. self.requestID = id(self)
  164. else:
  165. try:
  166. self.requestID = hash(requestID)
  167. except TypeError:
  168. raise TypeError("requestID must be hashable.")
  169. self.exception = False
  170. self.callback = callback
  171. self.exc_callback = exc_callback
  172. self.callable = callable_
  173. self.args = args or []
  174. self.kwds = kwds or {}
  175. def __str__(self):
  176. return "<WorkRequest id=%s args=%r kwargs=%r exception=%s>" % \
  177. (self.requestID, self.args, self.kwds, self.exception)
  178. class ThreadPool:
  179. """A thread pool, distributing work requests and collecting results.
  180. See the module docstring for more information.
  181. """
  182. def __init__(self, num_workers, q_size=0, resq_size=0, poll_timeout=5):
  183. """Set up the thread pool and start num_workers worker threads.
  184. ``num_workers`` is the number of worker threads to start initially.
  185. If ``q_size > 0`` the size of the work *request queue* is limited and
  186. the thread pool blocks when the queue is full and it tries to put
  187. more work requests in it (see ``putRequest`` method), unless you also
  188. use a positive ``timeout`` value for ``putRequest``.
  189. If ``resq_size > 0`` the size of the *results queue* is limited and the
  190. worker threads will block when the queue is full and they try to put
  191. new results in it.
  192. .. warning:
  193. If you set both ``q_size`` and ``resq_size`` to ``!= 0`` there is
  194. the possibilty of a deadlock, when the results queue is not pulled
  195. regularly and too many jobs are put in the work requests queue.
  196. To prevent this, always set ``timeout > 0`` when calling
  197. ``ThreadPool.putRequest()`` and catch ``Queue.Full`` exceptions.
  198. """
  199. self._requests_queue = Queue.Queue(q_size)
  200. self._results_queue = Queue.Queue(resq_size)
  201. self.workers = []
  202. self.dismissedWorkers = []
  203. self.workRequests = {}
  204. self.createWorkers(num_workers, poll_timeout)
  205. def createWorkers(self, num_workers, poll_timeout=5):
  206. """Add num_workers worker threads to the pool.
  207. ``poll_timout`` sets the interval in seconds (int or float) for how
  208. ofte threads should check whether they are dismissed, while waiting for
  209. requests.
  210. """
  211. for i in range(num_workers):
  212. self.workers.append(WorkerThread(self._requests_queue,
  213. self._results_queue, poll_timeout=poll_timeout))
  214. def dismissWorkers(self, num_workers, do_join=False):
  215. """Tell num_workers worker threads to quit after their current task."""
  216. dismiss_list = []
  217. for i in range(min(num_workers, len(self.workers))):
  218. worker = self.workers.pop()
  219. worker.dismiss()
  220. dismiss_list.append(worker)
  221. if do_join:
  222. for worker in dismiss_list:
  223. worker.join()
  224. else:
  225. self.dismissedWorkers.extend(dismiss_list)
  226. def joinAllDismissedWorkers(self):
  227. """Perform Thread.join() on all worker threads that have been dismissed.
  228. """
  229. for worker in self.dismissedWorkers:
  230. worker.join()
  231. self.dismissedWorkers = []
  232. def putRequest(self, request, block=True, timeout=None):
  233. """Put work request into work queue and save its id for later."""
  234. assert isinstance(request, WorkRequest)
  235. # don't reuse old work requests
  236. assert not getattr(request, 'exception', None)
  237. self._requests_queue.put(request, block, timeout)
  238. self.workRequests[request.requestID] = request
  239. def poll(self, block=False):
  240. """Process any new results in the queue."""
  241. while True:
  242. # still results pending?
  243. if not self.workRequests:
  244. raise NoResultsPending
  245. # are there still workers to process remaining requests?
  246. elif block and not self.workers:
  247. raise NoWorkersAvailable
  248. try:
  249. # get back next results
  250. request, result = self._results_queue.get(block=block)
  251. # has an exception occured?
  252. if request.exception and request.exc_callback:
  253. request.exc_callback(request, result)
  254. # hand results to callback, if any
  255. if request.callback and not \
  256. (request.exception and request.exc_callback):
  257. request.callback(request, result)
  258. del self.workRequests[request.requestID]
  259. #except Queue.Empty:
  260. except:
  261. break
  262. def wait(self):
  263. """Wait for results, blocking until all have arrived."""
  264. while 1:
  265. try:
  266. self.poll(True)
  267. except NoResultsPending:
  268. break
  269. ################
  270. # USAGE EXAMPLE
  271. ################
  272. if __name__ == '__main__':
  273. import random
  274. import time
  275. # the work the threads will have to do (rather trivial in our example)
  276. def do_something(data):
  277. time.sleep(random.randint(1,5))
  278. result = round(random.random() * data, 5)
  279. # just to show off, we throw an exception once in a while
  280. if result > 5:
  281. raise RuntimeError("Something extraordinary happened!")
  282. return result
  283. # this will be called each time a result is available
  284. def print_result(request, result):
  285. print("**** Result from request #%s: %r" % (request.requestID, result))
  286. # this will be called when an exception occurs within a thread
  287. # this example exception handler does little more than the default handler
  288. def handle_exception(request, exc_info):
  289. if not isinstance(exc_info, tuple):
  290. # Something is seriously wrong...
  291. print(request)
  292. print(exc_info)
  293. raise SystemExit
  294. print("**** Exception occured in request #%s: %s" % \
  295. (request.requestID, exc_info))
  296. # assemble the arguments for each job to a list...
  297. data = [random.randint(1,10) for i in range(20)]
  298. # ... and build a WorkRequest object for each item in data
  299. requests = makeRequests(do_something, data, print_result, handle_exception)
  300. # to use the default exception handler, uncomment next line and comment out
  301. # the preceding one.
  302. #requests = makeRequests(do_something, data, print_result)
  303. # or the other form of args_lists accepted by makeRequests: ((,), {})
  304. data = [((random.randint(1,10),), {}) for i in range(20)]
  305. requests.extend(
  306. makeRequests(do_something, data, print_result, handle_exception)
  307. #makeRequests(do_something, data, print_result)
  308. # to use the default exception handler, uncomment next line and comment
  309. # out the preceding one.
  310. )
  311. # we create a pool of 3 worker threads
  312. print("Creating thread pool with 3 worker threads.")
  313. main = ThreadPool(3)
  314. # then we put the work requests in the queue...
  315. for req in requests:
  316. main.putRequest(req)
  317. print("Work request #%s added." % req.requestID)
  318. # or shorter:
  319. # [main.putRequest(req) for req in requests]
  320. # ...and wait for the results to arrive in the result queue
  321. # by using ThreadPool.wait(). This would block until results for
  322. # all work requests have arrived:
  323. # main.wait()
  324. # instead we can poll for results while doing something else:
  325. i = 0
  326. while True:
  327. try:
  328. time.sleep(0.5)
  329. main.poll()
  330. print("Main thread working...")
  331. print("(active worker threads: %i)" % (threading.activeCount()-1, ))
  332. if i == 10:
  333. print("**** Adding 3 more worker threads...")
  334. main.createWorkers(3)
  335. if i == 20:
  336. print("**** Dismissing 2 worker threads...")
  337. main.dismissWorkers(2)
  338. i += 1
  339. except KeyboardInterrupt:
  340. print("**** Interrupted!")
  341. break
  342. except NoResultsPending:
  343. print("**** No pending results.")
  344. break
  345. if main.dismissedWorkers:
  346. print("Joining all dismissed worker threads...")
  347. main.joinAllDismissedWorkers()