您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

62 行
2.0KB

  1. from __future__ import print_function
  2. from eventlet import event as _event
  3. class metaphore(object):
  4. """This is sort of an inverse semaphore: a counter that starts at 0 and
  5. waits only if nonzero. It's used to implement a "wait for all" scenario.
  6. >>> from eventlet import coros, spawn_n
  7. >>> count = coros.metaphore()
  8. >>> count.wait()
  9. >>> def decrementer(count, id):
  10. ... print("{0} decrementing".format(id))
  11. ... count.dec()
  12. ...
  13. >>> _ = spawn_n(decrementer, count, 'A')
  14. >>> _ = spawn_n(decrementer, count, 'B')
  15. >>> count.inc(2)
  16. >>> count.wait()
  17. A decrementing
  18. B decrementing
  19. """
  20. def __init__(self):
  21. self.counter = 0
  22. self.event = _event.Event()
  23. # send() right away, else we'd wait on the default 0 count!
  24. self.event.send()
  25. def inc(self, by=1):
  26. """Increment our counter. If this transitions the counter from zero to
  27. nonzero, make any subsequent :meth:`wait` call wait.
  28. """
  29. assert by > 0
  30. self.counter += by
  31. if self.counter == by:
  32. # If we just incremented self.counter by 'by', and the new count
  33. # equals 'by', then the old value of self.counter was 0.
  34. # Transitioning from 0 to a nonzero value means wait() must
  35. # actually wait.
  36. self.event.reset()
  37. def dec(self, by=1):
  38. """Decrement our counter. If this transitions the counter from nonzero
  39. to zero, a current or subsequent wait() call need no longer wait.
  40. """
  41. assert by > 0
  42. self.counter -= by
  43. if self.counter <= 0:
  44. # Don't leave self.counter < 0, that will screw things up in
  45. # future calls.
  46. self.counter = 0
  47. # Transitioning from nonzero to 0 means wait() need no longer wait.
  48. self.event.send()
  49. def wait(self):
  50. """Suspend the caller only if our count is nonzero. In that case,
  51. resume the caller once the count decrements to zero again.
  52. """
  53. self.event.wait()