locks.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. # Copyright 2015 The Tornado Authors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  4. # not use this file except in compliance with the License. You may obtain
  5. # a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. # License for the specific language governing permissions and limitations
  13. # under the License.
  14. from __future__ import absolute_import, division, print_function, with_statement
  15. __all__ = ['Condition', 'Event', 'Semaphore', 'BoundedSemaphore', 'Lock']
  16. import collections
  17. from tornado import gen, ioloop
  18. from tornado.concurrent import Future
  19. class _TimeoutGarbageCollector(object):
  20. """Base class for objects that periodically clean up timed-out waiters.
  21. Avoids memory leak in a common pattern like:
  22. while True:
  23. yield condition.wait(short_timeout)
  24. print('looping....')
  25. """
  26. def __init__(self):
  27. self._waiters = collections.deque() # Futures.
  28. self._timeouts = 0
  29. def _garbage_collect(self):
  30. # Occasionally clear timed-out waiters.
  31. self._timeouts += 1
  32. if self._timeouts > 100:
  33. self._timeouts = 0
  34. self._waiters = collections.deque(
  35. w for w in self._waiters if not w.done())
  36. class Condition(_TimeoutGarbageCollector):
  37. """A condition allows one or more coroutines to wait until notified.
  38. Like a standard `threading.Condition`, but does not need an underlying lock
  39. that is acquired and released.
  40. With a `Condition`, coroutines can wait to be notified by other coroutines:
  41. .. testcode::
  42. from tornado import gen
  43. from tornado.ioloop import IOLoop
  44. from tornado.locks import Condition
  45. condition = Condition()
  46. @gen.coroutine
  47. def waiter():
  48. print("I'll wait right here")
  49. yield condition.wait() # Yield a Future.
  50. print("I'm done waiting")
  51. @gen.coroutine
  52. def notifier():
  53. print("About to notify")
  54. condition.notify()
  55. print("Done notifying")
  56. @gen.coroutine
  57. def runner():
  58. # Yield two Futures; wait for waiter() and notifier() to finish.
  59. yield [waiter(), notifier()]
  60. IOLoop.current().run_sync(runner)
  61. .. testoutput::
  62. I'll wait right here
  63. About to notify
  64. Done notifying
  65. I'm done waiting
  66. `wait` takes an optional ``timeout`` argument, which is either an absolute
  67. timestamp::
  68. io_loop = IOLoop.current()
  69. # Wait up to 1 second for a notification.
  70. yield condition.wait(timeout=io_loop.time() + 1)
  71. ...or a `datetime.timedelta` for a timeout relative to the current time::
  72. # Wait up to 1 second.
  73. yield condition.wait(timeout=datetime.timedelta(seconds=1))
  74. The method raises `tornado.gen.TimeoutError` if there's no notification
  75. before the deadline.
  76. """
  77. def __init__(self):
  78. super(Condition, self).__init__()
  79. self.io_loop = ioloop.IOLoop.current()
  80. def __repr__(self):
  81. result = '<%s' % (self.__class__.__name__, )
  82. if self._waiters:
  83. result += ' waiters[%s]' % len(self._waiters)
  84. return result + '>'
  85. def wait(self, timeout=None):
  86. """Wait for `.notify`.
  87. Returns a `.Future` that resolves ``True`` if the condition is notified,
  88. or ``False`` after a timeout.
  89. """
  90. waiter = Future()
  91. self._waiters.append(waiter)
  92. if timeout:
  93. def on_timeout():
  94. waiter.set_result(False)
  95. self._garbage_collect()
  96. io_loop = ioloop.IOLoop.current()
  97. timeout_handle = io_loop.add_timeout(timeout, on_timeout)
  98. waiter.add_done_callback(
  99. lambda _: io_loop.remove_timeout(timeout_handle))
  100. return waiter
  101. def notify(self, n=1):
  102. """Wake ``n`` waiters."""
  103. waiters = [] # Waiters we plan to run right now.
  104. while n and self._waiters:
  105. waiter = self._waiters.popleft()
  106. if not waiter.done(): # Might have timed out.
  107. n -= 1
  108. waiters.append(waiter)
  109. for waiter in waiters:
  110. waiter.set_result(True)
  111. def notify_all(self):
  112. """Wake all waiters."""
  113. self.notify(len(self._waiters))
  114. class Event(object):
  115. """An event blocks coroutines until its internal flag is set to True.
  116. Similar to `threading.Event`.
  117. A coroutine can wait for an event to be set. Once it is set, calls to
  118. ``yield event.wait()`` will not block unless the event has been cleared:
  119. .. testcode::
  120. from tornado import gen
  121. from tornado.ioloop import IOLoop
  122. from tornado.locks import Event
  123. event = Event()
  124. @gen.coroutine
  125. def waiter():
  126. print("Waiting for event")
  127. yield event.wait()
  128. print("Not waiting this time")
  129. yield event.wait()
  130. print("Done")
  131. @gen.coroutine
  132. def setter():
  133. print("About to set the event")
  134. event.set()
  135. @gen.coroutine
  136. def runner():
  137. yield [waiter(), setter()]
  138. IOLoop.current().run_sync(runner)
  139. .. testoutput::
  140. Waiting for event
  141. About to set the event
  142. Not waiting this time
  143. Done
  144. """
  145. def __init__(self):
  146. self._future = Future()
  147. def __repr__(self):
  148. return '<%s %s>' % (
  149. self.__class__.__name__, 'set' if self.is_set() else 'clear')
  150. def is_set(self):
  151. """Return ``True`` if the internal flag is true."""
  152. return self._future.done()
  153. def set(self):
  154. """Set the internal flag to ``True``. All waiters are awakened.
  155. Calling `.wait` once the flag is set will not block.
  156. """
  157. if not self._future.done():
  158. self._future.set_result(None)
  159. def clear(self):
  160. """Reset the internal flag to ``False``.
  161. Calls to `.wait` will block until `.set` is called.
  162. """
  163. if self._future.done():
  164. self._future = Future()
  165. def wait(self, timeout=None):
  166. """Block until the internal flag is true.
  167. Returns a Future, which raises `tornado.gen.TimeoutError` after a
  168. timeout.
  169. """
  170. if timeout is None:
  171. return self._future
  172. else:
  173. return gen.with_timeout(timeout, self._future)
  174. class _ReleasingContextManager(object):
  175. """Releases a Lock or Semaphore at the end of a "with" statement.
  176. with (yield semaphore.acquire()):
  177. pass
  178. # Now semaphore.release() has been called.
  179. """
  180. def __init__(self, obj):
  181. self._obj = obj
  182. def __enter__(self):
  183. pass
  184. def __exit__(self, exc_type, exc_val, exc_tb):
  185. self._obj.release()
  186. class Semaphore(_TimeoutGarbageCollector):
  187. """A lock that can be acquired a fixed number of times before blocking.
  188. A Semaphore manages a counter representing the number of `.release` calls
  189. minus the number of `.acquire` calls, plus an initial value. The `.acquire`
  190. method blocks if necessary until it can return without making the counter
  191. negative.
  192. Semaphores limit access to a shared resource. To allow access for two
  193. workers at a time:
  194. .. testsetup:: semaphore
  195. from collections import deque
  196. from tornado import gen
  197. from tornado.ioloop import IOLoop
  198. from tornado.concurrent import Future
  199. # Ensure reliable doctest output: resolve Futures one at a time.
  200. futures_q = deque([Future() for _ in range(3)])
  201. @gen.coroutine
  202. def simulator(futures):
  203. for f in futures:
  204. yield gen.moment
  205. f.set_result(None)
  206. IOLoop.current().add_callback(simulator, list(futures_q))
  207. def use_some_resource():
  208. return futures_q.popleft()
  209. .. testcode:: semaphore
  210. from tornado import gen
  211. from tornado.ioloop import IOLoop
  212. from tornado.locks import Semaphore
  213. sem = Semaphore(2)
  214. @gen.coroutine
  215. def worker(worker_id):
  216. yield sem.acquire()
  217. try:
  218. print("Worker %d is working" % worker_id)
  219. yield use_some_resource()
  220. finally:
  221. print("Worker %d is done" % worker_id)
  222. sem.release()
  223. @gen.coroutine
  224. def runner():
  225. # Join all workers.
  226. yield [worker(i) for i in range(3)]
  227. IOLoop.current().run_sync(runner)
  228. .. testoutput:: semaphore
  229. Worker 0 is working
  230. Worker 1 is working
  231. Worker 0 is done
  232. Worker 2 is working
  233. Worker 1 is done
  234. Worker 2 is done
  235. Workers 0 and 1 are allowed to run concurrently, but worker 2 waits until
  236. the semaphore has been released once, by worker 0.
  237. `.acquire` is a context manager, so ``worker`` could be written as::
  238. @gen.coroutine
  239. def worker(worker_id):
  240. with (yield sem.acquire()):
  241. print("Worker %d is working" % worker_id)
  242. yield use_some_resource()
  243. # Now the semaphore has been released.
  244. print("Worker %d is done" % worker_id)
  245. In Python 3.5, the semaphore itself can be used as an async context
  246. manager::
  247. async def worker(worker_id):
  248. async with sem:
  249. print("Worker %d is working" % worker_id)
  250. await use_some_resource()
  251. # Now the semaphore has been released.
  252. print("Worker %d is done" % worker_id)
  253. .. versionchanged:: 4.3
  254. Added ``async with`` support in Python 3.5.
  255. """
  256. def __init__(self, value=1):
  257. super(Semaphore, self).__init__()
  258. if value < 0:
  259. raise ValueError('semaphore initial value must be >= 0')
  260. self._value = value
  261. def __repr__(self):
  262. res = super(Semaphore, self).__repr__()
  263. extra = 'locked' if self._value == 0 else 'unlocked,value:{0}'.format(
  264. self._value)
  265. if self._waiters:
  266. extra = '{0},waiters:{1}'.format(extra, len(self._waiters))
  267. return '<{0} [{1}]>'.format(res[1:-1], extra)
  268. def release(self):
  269. """Increment the counter and wake one waiter."""
  270. self._value += 1
  271. while self._waiters:
  272. waiter = self._waiters.popleft()
  273. if not waiter.done():
  274. self._value -= 1
  275. # If the waiter is a coroutine paused at
  276. #
  277. # with (yield semaphore.acquire()):
  278. #
  279. # then the context manager's __exit__ calls release() at the end
  280. # of the "with" block.
  281. waiter.set_result(_ReleasingContextManager(self))
  282. break
  283. def acquire(self, timeout=None):
  284. """Decrement the counter. Returns a Future.
  285. Block if the counter is zero and wait for a `.release`. The Future
  286. raises `.TimeoutError` after the deadline.
  287. """
  288. waiter = Future()
  289. if self._value > 0:
  290. self._value -= 1
  291. waiter.set_result(_ReleasingContextManager(self))
  292. else:
  293. self._waiters.append(waiter)
  294. if timeout:
  295. def on_timeout():
  296. waiter.set_exception(gen.TimeoutError())
  297. self._garbage_collect()
  298. io_loop = ioloop.IOLoop.current()
  299. timeout_handle = io_loop.add_timeout(timeout, on_timeout)
  300. waiter.add_done_callback(
  301. lambda _: io_loop.remove_timeout(timeout_handle))
  302. return waiter
  303. def __enter__(self):
  304. raise RuntimeError(
  305. "Use Semaphore like 'with (yield semaphore.acquire())', not like"
  306. " 'with semaphore'")
  307. __exit__ = __enter__
  308. @gen.coroutine
  309. def __aenter__(self):
  310. yield self.acquire()
  311. @gen.coroutine
  312. def __aexit__(self, typ, value, tb):
  313. self.release()
  314. class BoundedSemaphore(Semaphore):
  315. """A semaphore that prevents release() being called too many times.
  316. If `.release` would increment the semaphore's value past the initial
  317. value, it raises `ValueError`. Semaphores are mostly used to guard
  318. resources with limited capacity, so a semaphore released too many times
  319. is a sign of a bug.
  320. """
  321. def __init__(self, value=1):
  322. super(BoundedSemaphore, self).__init__(value=value)
  323. self._initial_value = value
  324. def release(self):
  325. """Increment the counter and wake one waiter."""
  326. if self._value >= self._initial_value:
  327. raise ValueError("Semaphore released too many times")
  328. super(BoundedSemaphore, self).release()
  329. class Lock(object):
  330. """A lock for coroutines.
  331. A Lock begins unlocked, and `acquire` locks it immediately. While it is
  332. locked, a coroutine that yields `acquire` waits until another coroutine
  333. calls `release`.
  334. Releasing an unlocked lock raises `RuntimeError`.
  335. `acquire` supports the context manager protocol in all Python versions:
  336. >>> from tornado import gen, locks
  337. >>> lock = locks.Lock()
  338. >>>
  339. >>> @gen.coroutine
  340. ... def f():
  341. ... with (yield lock.acquire()):
  342. ... # Do something holding the lock.
  343. ... pass
  344. ...
  345. ... # Now the lock is released.
  346. In Python 3.5, `Lock` also supports the async context manager
  347. protocol. Note that in this case there is no `acquire`, because
  348. ``async with`` includes both the ``yield`` and the ``acquire``
  349. (just as it does with `threading.Lock`):
  350. >>> async def f(): # doctest: +SKIP
  351. ... async with lock:
  352. ... # Do something holding the lock.
  353. ... pass
  354. ...
  355. ... # Now the lock is released.
  356. .. versionchanged:: 3.5
  357. Added ``async with`` support in Python 3.5.
  358. """
  359. def __init__(self):
  360. self._block = BoundedSemaphore(value=1)
  361. def __repr__(self):
  362. return "<%s _block=%s>" % (
  363. self.__class__.__name__,
  364. self._block)
  365. def acquire(self, timeout=None):
  366. """Attempt to lock. Returns a Future.
  367. Returns a Future, which raises `tornado.gen.TimeoutError` after a
  368. timeout.
  369. """
  370. return self._block.acquire(timeout)
  371. def release(self):
  372. """Unlock.
  373. The first coroutine in line waiting for `acquire` gets the lock.
  374. If not locked, raise a `RuntimeError`.
  375. """
  376. try:
  377. self._block.release()
  378. except ValueError:
  379. raise RuntimeError('release unlocked lock')
  380. def __enter__(self):
  381. raise RuntimeError(
  382. "Use Lock like 'with (yield lock)', not like 'with lock'")
  383. __exit__ = __enter__
  384. @gen.coroutine
  385. def __aenter__(self):
  386. yield self.acquire()
  387. @gen.coroutine
  388. def __aexit__(self, typ, value, tb):
  389. self.release()