threadpool.py 17 KB

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