unsafe_thread_pool_executor.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. # Copyright 2009 Brian Quinlan. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. #
  4. # Copyright (C) 2013 Google Inc.
  5. # Changes to this file are licensed under the same terms as the original file
  6. # (the Python Software Foundation License).
  7. from __future__ import with_statement
  8. import threading
  9. import weakref
  10. import sys
  11. from concurrent.futures import _base
  12. try:
  13. import queue
  14. except ImportError:
  15. import Queue as queue
  16. # This file provides an UnsafeThreadPoolExecutor, which operates exactly like
  17. # the upstream Python version of ThreadPoolExecutor with one exception: it
  18. # doesn't wait for worker threads to finish before shutting down the Python
  19. # interpreter.
  20. #
  21. # This is dangerous for many workloads, but fine for some (like when threads
  22. # only send network requests). The YCM workload is one of those workloads where
  23. # it's safe (the aforementioned network requests case).
  24. class _WorkItem( object ):
  25. def __init__( self, future, fn, args, kwargs ):
  26. self.future = future
  27. self.fn = fn
  28. self.args = args
  29. self.kwargs = kwargs
  30. def run( self ):
  31. if not self.future.set_running_or_notify_cancel():
  32. return
  33. try:
  34. result = self.fn( *self.args, **self.kwargs )
  35. except BaseException:
  36. e = sys.exc_info()[ 1 ]
  37. self.future.set_exception( e )
  38. else:
  39. self.future.set_result( result )
  40. def _worker( executor_reference, work_queue ):
  41. try:
  42. while True:
  43. work_item = work_queue.get( block=True )
  44. if work_item is not None:
  45. work_item.run()
  46. continue
  47. executor = executor_reference()
  48. # Exit if:
  49. # - The executor that owns the worker has been collected OR
  50. # - The executor that owns the worker has been shutdown.
  51. if executor is None or executor._shutdown:
  52. # Notice other workers
  53. work_queue.put( None )
  54. return
  55. del executor
  56. except BaseException:
  57. _base.LOGGER.critical( 'Exception in worker', exc_info=True )
  58. class UnsafeThreadPoolExecutor( _base.Executor ):
  59. def __init__( self, max_workers ):
  60. """Initializes a new ThreadPoolExecutor instance.
  61. Args:
  62. max_workers: The maximum number of threads that can be used to
  63. execute the given calls.
  64. """
  65. self._max_workers = max_workers
  66. self._work_queue = queue.Queue()
  67. self._threads = set()
  68. self._shutdown = False
  69. self._shutdown_lock = threading.Lock()
  70. def submit( self, fn, *args, **kwargs ):
  71. with self._shutdown_lock:
  72. if self._shutdown:
  73. raise RuntimeError( 'cannot schedule new futures after shutdown' )
  74. f = _base.Future()
  75. w = _WorkItem( f, fn, args, kwargs )
  76. self._work_queue.put( w )
  77. self._adjust_thread_count()
  78. return f
  79. submit.__doc__ = _base.Executor.submit.__doc__
  80. def _adjust_thread_count( self ):
  81. # When the executor gets lost, the weakref callback will wake up
  82. # the worker threads.
  83. def weakref_cb( _, q=self._work_queue ):
  84. q.put( None )
  85. # TODO(bquinlan): Should avoid creating new threads if there are more
  86. # idle threads than items in the work queue.
  87. if len( self._threads ) < self._max_workers:
  88. t = threading.Thread( target=_worker,
  89. args=( weakref.ref( self, weakref_cb ),
  90. self._work_queue ) )
  91. t.daemon = True
  92. t.start()
  93. self._threads.add( t )
  94. def shutdown( self, wait=True ):
  95. with self._shutdown_lock:
  96. self._shutdown = True
  97. self._work_queue.put( None )
  98. if wait:
  99. for t in self._threads:
  100. t.join()
  101. shutdown.__doc__ = _base.Executor.shutdown.__doc__