|
| 1 | + |
| 2 | +import logging |
| 3 | +import random |
| 4 | +import threading |
| 5 | +import time |
| 6 | + |
| 7 | +logging.basicConfig(level=logging.DEBUG, |
| 8 | + format='%(asctime)s (%(threadName)-2s) %(message)s', |
| 9 | + ) |
| 10 | + |
| 11 | +class ActivePool(object): |
| 12 | + def __init__(self): |
| 13 | + super(ActivePool, self).__init__() |
| 14 | + self.active = [] |
| 15 | + self.lock = threading.Lock() |
| 16 | + def makeActive(self, name): |
| 17 | + with self.lock: |
| 18 | + self.active.append(name) |
| 19 | + logging.debug('Running: %s', self.active) |
| 20 | + def makeInactive(self, name): |
| 21 | + with self.lock: |
| 22 | + self.active.remove(name) |
| 23 | + logging.debug('Running: %s', self.active) |
| 24 | + |
| 25 | +def worker(s, pool): |
| 26 | + logging.debug('Waiting to join the pool') |
| 27 | + with s: |
| 28 | + name = threading.currentThread().getName() |
| 29 | + pool.makeActive(name) |
| 30 | + time.sleep(0.1) |
| 31 | + pool.makeInactive(name) |
| 32 | + |
| 33 | +pool = ActivePool() |
| 34 | +s = threading.Semaphore(2) |
| 35 | +for i in range(4): |
| 36 | + t = threading.Thread(target=worker, name=str(i), args=(s, pool)) |
| 37 | + t.start() |
| 38 | + |
0 commit comments