unsafe_thread_pool_executor.py 3.5 KB

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