threads.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.concurrency.threads
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Pool implementation using threads.
  6. """
  7. from __future__ import absolute_import
  8. from celery.utils.compat import UserDict
  9. from .base import apply_target, BasePool
  10. class NullDict(UserDict):
  11. def __setitem__(self, key, value):
  12. pass
  13. class TaskPool(BasePool):
  14. def __init__(self, *args, **kwargs):
  15. try:
  16. import threadpool
  17. except ImportError:
  18. raise ImportError(
  19. 'The threaded pool requires the threadpool module.')
  20. self.WorkRequest = threadpool.WorkRequest
  21. self.ThreadPool = threadpool.ThreadPool
  22. super(TaskPool, self).__init__(*args, **kwargs)
  23. def on_start(self):
  24. self._pool = self.ThreadPool(self.limit)
  25. # threadpool stores all work requests until they are processed
  26. # we don't need this dict, and it occupies way too much memory.
  27. self._pool.workRequests = NullDict()
  28. self._quick_put = self._pool.putRequest
  29. self._quick_clear = self._pool._results_queue.queue.clear
  30. def on_stop(self):
  31. self._pool.dismissWorkers(self.limit, do_join=True)
  32. def on_apply(self, target, args=None, kwargs=None, callback=None,
  33. accept_callback=None, **_):
  34. req = self.WorkRequest(apply_target, (target, args, kwargs, callback,
  35. accept_callback))
  36. self._quick_put(req)
  37. # threadpool also has callback support,
  38. # but for some reason the callback is not triggered
  39. # before you've collected the results.
  40. # Clear the results (if any), so it doesn't grow too large.
  41. self._quick_clear()
  42. return req