_threading.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. """A clone of threading module (version 2.7.2) that always
  2. targets real OS threads. (Unlike 'threading' which flips between
  3. green and OS threads based on whether the monkey patching is in effect
  4. or not).
  5. This module is missing 'Thread' class, but includes 'Queue'.
  6. """
  7. from __future__ import absolute_import
  8. try:
  9. from Queue import Full, Empty
  10. except ImportError:
  11. from queue import Full, Empty # pylint:disable=import-error
  12. from collections import deque
  13. import heapq
  14. from time import time as _time, sleep as _sleep
  15. from gevent import monkey
  16. from gevent._compat import PY3
  17. __all__ = ['Condition',
  18. 'Event',
  19. 'Lock',
  20. 'RLock',
  21. 'Semaphore',
  22. 'BoundedSemaphore',
  23. 'Queue',
  24. 'local',
  25. 'stack_size']
  26. thread_name = '_thread' if PY3 else 'thread'
  27. start_new_thread, Lock, get_ident, local, stack_size = monkey.get_original(thread_name, [
  28. 'start_new_thread', 'allocate_lock', 'get_ident', '_local', 'stack_size'])
  29. class RLock(object):
  30. def __init__(self):
  31. self.__block = Lock()
  32. self.__owner = None
  33. self.__count = 0
  34. def __repr__(self):
  35. owner = self.__owner
  36. return "<%s owner=%r count=%d>" % (
  37. self.__class__.__name__, owner, self.__count)
  38. def acquire(self, blocking=1):
  39. me = get_ident()
  40. if self.__owner == me:
  41. self.__count = self.__count + 1
  42. return 1
  43. rc = self.__block.acquire(blocking)
  44. if rc:
  45. self.__owner = me
  46. self.__count = 1
  47. return rc
  48. __enter__ = acquire
  49. def release(self):
  50. if self.__owner != get_ident():
  51. raise RuntimeError("cannot release un-acquired lock")
  52. self.__count = count = self.__count - 1
  53. if not count:
  54. self.__owner = None
  55. self.__block.release()
  56. def __exit__(self, t, v, tb):
  57. self.release()
  58. # Internal methods used by condition variables
  59. def _acquire_restore(self, count_owner):
  60. count, owner = count_owner
  61. self.__block.acquire()
  62. self.__count = count
  63. self.__owner = owner
  64. def _release_save(self):
  65. count = self.__count
  66. self.__count = 0
  67. owner = self.__owner
  68. self.__owner = None
  69. self.__block.release()
  70. return (count, owner)
  71. def _is_owned(self):
  72. return self.__owner == get_ident()
  73. class Condition(object):
  74. # pylint:disable=method-hidden
  75. def __init__(self, lock=None):
  76. if lock is None:
  77. lock = RLock()
  78. self.__lock = lock
  79. # Export the lock's acquire() and release() methods
  80. self.acquire = lock.acquire
  81. self.release = lock.release
  82. # If the lock defines _release_save() and/or _acquire_restore(),
  83. # these override the default implementations (which just call
  84. # release() and acquire() on the lock). Ditto for _is_owned().
  85. try:
  86. self._release_save = lock._release_save
  87. except AttributeError:
  88. pass
  89. try:
  90. self._acquire_restore = lock._acquire_restore
  91. except AttributeError:
  92. pass
  93. try:
  94. self._is_owned = lock._is_owned
  95. except AttributeError:
  96. pass
  97. self.__waiters = []
  98. def __enter__(self):
  99. return self.__lock.__enter__()
  100. def __exit__(self, *args):
  101. return self.__lock.__exit__(*args)
  102. def __repr__(self):
  103. return "<Condition(%s, %d)>" % (self.__lock, len(self.__waiters))
  104. def _release_save(self):
  105. self.__lock.release() # No state to save
  106. def _acquire_restore(self, x): # pylint:disable=unused-argument
  107. self.__lock.acquire() # Ignore saved state
  108. def _is_owned(self):
  109. # Return True if lock is owned by current_thread.
  110. # This method is called only if __lock doesn't have _is_owned().
  111. if self.__lock.acquire(0):
  112. self.__lock.release()
  113. return False
  114. return True
  115. def wait(self, timeout=None):
  116. if not self._is_owned():
  117. raise RuntimeError("cannot wait on un-acquired lock")
  118. waiter = Lock()
  119. waiter.acquire()
  120. self.__waiters.append(waiter)
  121. saved_state = self._release_save()
  122. try: # restore state no matter what (e.g., KeyboardInterrupt)
  123. if timeout is None:
  124. waiter.acquire()
  125. else:
  126. # Balancing act: We can't afford a pure busy loop, so we
  127. # have to sleep; but if we sleep the whole timeout time,
  128. # we'll be unresponsive. The scheme here sleeps very
  129. # little at first, longer as time goes on, but never longer
  130. # than 20 times per second (or the timeout time remaining).
  131. endtime = _time() + timeout
  132. delay = 0.0005 # 500 us -> initial delay of 1 ms
  133. while True:
  134. gotit = waiter.acquire(0)
  135. if gotit:
  136. break
  137. remaining = endtime - _time()
  138. if remaining <= 0:
  139. break
  140. delay = min(delay * 2, remaining, .05)
  141. _sleep(delay)
  142. if not gotit:
  143. try:
  144. self.__waiters.remove(waiter)
  145. except ValueError:
  146. pass
  147. finally:
  148. self._acquire_restore(saved_state)
  149. def notify(self, n=1):
  150. if not self._is_owned():
  151. raise RuntimeError("cannot notify on un-acquired lock")
  152. __waiters = self.__waiters
  153. waiters = __waiters[:n]
  154. if not waiters:
  155. return
  156. for waiter in waiters:
  157. waiter.release()
  158. try:
  159. __waiters.remove(waiter)
  160. except ValueError:
  161. pass
  162. def notify_all(self):
  163. self.notify(len(self.__waiters))
  164. class Semaphore(object):
  165. # After Tim Peters' semaphore class, but not quite the same (no maximum)
  166. def __init__(self, value=1):
  167. if value < 0:
  168. raise ValueError("semaphore initial value must be >= 0")
  169. self.__cond = Condition(Lock())
  170. self.__value = value
  171. def acquire(self, blocking=1):
  172. rc = False
  173. self.__cond.acquire()
  174. while self.__value == 0:
  175. if not blocking:
  176. break
  177. self.__cond.wait()
  178. else:
  179. self.__value = self.__value - 1
  180. rc = True
  181. self.__cond.release()
  182. return rc
  183. __enter__ = acquire
  184. def release(self):
  185. self.__cond.acquire()
  186. self.__value = self.__value + 1
  187. self.__cond.notify()
  188. self.__cond.release()
  189. def __exit__(self, t, v, tb):
  190. self.release()
  191. class BoundedSemaphore(Semaphore):
  192. """Semaphore that checks that # releases is <= # acquires"""
  193. def __init__(self, value=1):
  194. Semaphore.__init__(self, value)
  195. self._initial_value = value
  196. def release(self):
  197. if self.Semaphore__value >= self._initial_value: # pylint:disable=no-member
  198. raise ValueError("Semaphore released too many times")
  199. return Semaphore.release(self)
  200. class Event(object):
  201. # After Tim Peters' event class (without is_posted())
  202. def __init__(self):
  203. self.__cond = Condition(Lock())
  204. self.__flag = False
  205. def _reset_internal_locks(self):
  206. # private! called by Thread._reset_internal_locks by _after_fork()
  207. self.__cond.__init__()
  208. def is_set(self):
  209. return self.__flag
  210. def set(self):
  211. self.__cond.acquire()
  212. try:
  213. self.__flag = True
  214. self.__cond.notify_all()
  215. finally:
  216. self.__cond.release()
  217. def clear(self):
  218. self.__cond.acquire()
  219. try:
  220. self.__flag = False
  221. finally:
  222. self.__cond.release()
  223. def wait(self, timeout=None):
  224. self.__cond.acquire()
  225. try:
  226. if not self.__flag:
  227. self.__cond.wait(timeout)
  228. return self.__flag
  229. finally:
  230. self.__cond.release()
  231. class Queue: # pylint:disable=old-style-class
  232. """Create a queue object with a given maximum size.
  233. If maxsize is <= 0, the queue size is infinite.
  234. """
  235. def __init__(self, maxsize=0):
  236. self.maxsize = maxsize
  237. self._init(maxsize)
  238. # mutex must be held whenever the queue is mutating. All methods
  239. # that acquire mutex must release it before returning. mutex
  240. # is shared between the three conditions, so acquiring and
  241. # releasing the conditions also acquires and releases mutex.
  242. self.mutex = Lock()
  243. # Notify not_empty whenever an item is added to the queue; a
  244. # thread waiting to get is notified then.
  245. self.not_empty = Condition(self.mutex)
  246. # Notify not_full whenever an item is removed from the queue;
  247. # a thread waiting to put is notified then.
  248. self.not_full = Condition(self.mutex)
  249. # Notify all_tasks_done whenever the number of unfinished tasks
  250. # drops to zero; thread waiting to join() is notified to resume
  251. self.all_tasks_done = Condition(self.mutex)
  252. self.unfinished_tasks = 0
  253. def task_done(self):
  254. """Indicate that a formerly enqueued task is complete.
  255. Used by Queue consumer threads. For each get() used to fetch a task,
  256. a subsequent call to task_done() tells the queue that the processing
  257. on the task is complete.
  258. If a join() is currently blocking, it will resume when all items
  259. have been processed (meaning that a task_done() call was received
  260. for every item that had been put() into the queue).
  261. Raises a ValueError if called more times than there were items
  262. placed in the queue.
  263. """
  264. self.all_tasks_done.acquire()
  265. try:
  266. unfinished = self.unfinished_tasks - 1
  267. if unfinished <= 0:
  268. if unfinished < 0:
  269. raise ValueError('task_done() called too many times')
  270. self.all_tasks_done.notify_all()
  271. self.unfinished_tasks = unfinished
  272. finally:
  273. self.all_tasks_done.release()
  274. def join(self):
  275. """Blocks until all items in the Queue have been gotten and processed.
  276. The count of unfinished tasks goes up whenever an item is added to the
  277. queue. The count goes down whenever a consumer thread calls task_done()
  278. to indicate the item was retrieved and all work on it is complete.
  279. When the count of unfinished tasks drops to zero, join() unblocks.
  280. """
  281. self.all_tasks_done.acquire()
  282. try:
  283. while self.unfinished_tasks:
  284. self.all_tasks_done.wait()
  285. finally:
  286. self.all_tasks_done.release()
  287. def qsize(self):
  288. """Return the approximate size of the queue (not reliable!)."""
  289. self.mutex.acquire()
  290. try:
  291. return self._qsize()
  292. finally:
  293. self.mutex.release()
  294. def empty(self):
  295. """Return True if the queue is empty, False otherwise (not reliable!)."""
  296. self.mutex.acquire()
  297. try:
  298. return not self._qsize()
  299. finally:
  300. self.mutex.release()
  301. def full(self):
  302. """Return True if the queue is full, False otherwise (not reliable!)."""
  303. self.mutex.acquire()
  304. try:
  305. if self.maxsize <= 0:
  306. return False
  307. if self.maxsize >= self._qsize():
  308. return True
  309. finally:
  310. self.mutex.release()
  311. def put(self, item, block=True, timeout=None):
  312. """Put an item into the queue.
  313. If optional args 'block' is true and 'timeout' is None (the default),
  314. block if necessary until a free slot is available. If 'timeout' is
  315. a positive number, it blocks at most 'timeout' seconds and raises
  316. the Full exception if no free slot was available within that time.
  317. Otherwise ('block' is false), put an item on the queue if a free slot
  318. is immediately available, else raise the Full exception ('timeout'
  319. is ignored in that case).
  320. """
  321. self.not_full.acquire()
  322. try:
  323. if self.maxsize > 0:
  324. if not block:
  325. if self._qsize() >= self.maxsize:
  326. raise Full
  327. elif timeout is None:
  328. while self._qsize() >= self.maxsize:
  329. self.not_full.wait()
  330. elif timeout < 0:
  331. raise ValueError("'timeout' must be a positive number")
  332. else:
  333. endtime = _time() + timeout
  334. while self._qsize() >= self.maxsize:
  335. remaining = endtime - _time()
  336. if remaining <= 0.0:
  337. raise Full
  338. self.not_full.wait(remaining)
  339. self._put(item)
  340. self.unfinished_tasks += 1
  341. self.not_empty.notify()
  342. finally:
  343. self.not_full.release()
  344. def put_nowait(self, item):
  345. """Put an item into the queue without blocking.
  346. Only enqueue the item if a free slot is immediately available.
  347. Otherwise raise the Full exception.
  348. """
  349. return self.put(item, False)
  350. def get(self, block=True, timeout=None):
  351. """Remove and return an item from the queue.
  352. If optional args 'block' is true and 'timeout' is None (the default),
  353. block if necessary until an item is available. If 'timeout' is
  354. a positive number, it blocks at most 'timeout' seconds and raises
  355. the Empty exception if no item was available within that time.
  356. Otherwise ('block' is false), return an item if one is immediately
  357. available, else raise the Empty exception ('timeout' is ignored
  358. in that case).
  359. """
  360. self.not_empty.acquire()
  361. try:
  362. if not block:
  363. if not self._qsize():
  364. raise Empty
  365. elif timeout is None:
  366. while not self._qsize():
  367. self.not_empty.wait()
  368. elif timeout < 0:
  369. raise ValueError("'timeout' must be a positive number")
  370. else:
  371. endtime = _time() + timeout
  372. while not self._qsize():
  373. remaining = endtime - _time()
  374. if remaining <= 0.0:
  375. raise Empty
  376. self.not_empty.wait(remaining)
  377. item = self._get()
  378. self.not_full.notify()
  379. return item
  380. finally:
  381. self.not_empty.release()
  382. def get_nowait(self):
  383. """Remove and return an item from the queue without blocking.
  384. Only get an item if one is immediately available. Otherwise
  385. raise the Empty exception.
  386. """
  387. return self.get(False)
  388. # Override these methods to implement other queue organizations
  389. # (e.g. stack or priority queue).
  390. # These will only be called with appropriate locks held
  391. # Initialize the queue representation
  392. def _init(self, maxsize):
  393. # pylint:disable=unused-argument
  394. self.queue = deque()
  395. def _qsize(self, len=len):
  396. return len(self.queue)
  397. # Put a new item in the queue
  398. def _put(self, item):
  399. self.queue.append(item)
  400. # Get an item from the queue
  401. def _get(self):
  402. return self.queue.popleft()
  403. class PriorityQueue(Queue):
  404. '''Variant of Queue that retrieves open entries in priority order (lowest first).
  405. Entries are typically tuples of the form: (priority number, data).
  406. '''
  407. def _init(self, maxsize):
  408. self.queue = []
  409. def _qsize(self, len=len):
  410. return len(self.queue)
  411. def _put(self, item, heappush=heapq.heappush):
  412. # pylint:disable=arguments-differ
  413. heappush(self.queue, item)
  414. def _get(self, heappop=heapq.heappop):
  415. # pylint:disable=arguments-differ
  416. return heappop(self.queue)
  417. class LifoQueue(Queue):
  418. '''Variant of Queue that retrieves most recently added entries first.'''
  419. def _init(self, maxsize):
  420. self.queue = []
  421. def _qsize(self, len=len):
  422. return len(self.queue)
  423. def _put(self, item):
  424. self.queue.append(item)
  425. def _get(self):
  426. return self.queue.pop()