Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import asyncio
- import random
- PARALLEL = 3
- session_pool = []
- pool_queue = asyncio.Queue()
- for i in range(PARALLEL):
- session_pool.append({
- 'place': None,
- # some other data here
- })
- @asyncio.coroutine
- def pool_job(coro, chosenN):
- r = yield from coro
- session_pool[chosenN]['place'] = None
- print('Free {}'.format(chosenN))
- return r
- def pick_free_pool_place():
- for i in range(PARALLEL):
- if session_pool[i]['place'] is None:
- return i
- return None
- @asyncio.coroutine
- def pool_manager():
- while True:
- coro = yield from pool_queue.get()
- chosenN = pick_free_pool_place()
- if chosenN is None:
- yield from asyncio.wait(
- [r['place'] for r in session_pool if r['place'] is not None],
- return_when=asyncio.FIRST_COMPLETED
- )
- chosenN = pick_free_pool_place()
- sr = session_pool[chosenN]
- task = asyncio.async(pool_job(coro, chosenN))
- sr['place'] = task
- print('Apply for {}'.format(chosenN))
- @asyncio.coroutine
- def main():
- task_count = 0
- quit = asyncio.Event()
- @asyncio.coroutine
- def enqueue_test_task(coro):
- nonlocal task_count
- task_count += 1
- @asyncio.coroutine
- def f():
- nonlocal task_count
- yield from coro
- task_count -= 1
- if task_count <= 0:
- quit.set()
- yield from pool_queue.put(f())
- for i in range(10):
- yield from enqueue_test_task(asyncio.sleep(random.randint(1, 4)))
- yield from quit.wait()
- loop = asyncio.get_event_loop()
- asyncio.async(pool_manager())
- loop.run_until_complete(main())
- loop.close()
Advertisement
Add Comment
Please, Sign In to add comment