Advertisement
Guest User

Untitled

a guest
May 22nd, 2015
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. #
  4. # Copyright (c) 2008 Doug Hellmann All rights reserved.
  5. #
  6. """Multiple concurrent access to a resource
  7. """
  8. #end_pymotw_header
  9. import logging
  10. import random
  11. import threading
  12. import time
  13.  
  14. logging.basicConfig(
  15. level=logging.DEBUG,
  16. format='%(asctime)s (%(threadName)-2s) %(message)s',
  17. )
  18.  
  19. class ActivePool(object):
  20. def __init__(self):
  21. super(ActivePool, self).__init__()
  22. self.active = []
  23. self.lock = threading.Lock()
  24. def makeActive(self, name):
  25. with self.lock:
  26. self.active.append(name)
  27. logging.debug('Running: %s', self.active)
  28. def makeInactive(self, name):
  29. with self.lock:
  30. self.active.remove(name)
  31. logging.debug('Running: %s', self.active)
  32.  
  33. def worker(s, pool):
  34. logging.debug('Waiting to join the pool')
  35. with s:
  36. name = threading.currentThread().getName()
  37. pool.makeActive(name)
  38. time.sleep(0.1)
  39. pool.makeInactive(name)
  40.  
  41. pool = ActivePool()
  42. s = threading.Semaphore(2)
  43. for i in range(4):
  44. t = threading.Thread(target=worker,
  45. name=str(i),
  46. args=(s, pool))
  47. t.start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement