0

I am trying to reuse the code shown in the following SO post answer:

Especially the semaphore part that does:

async with sema, session.get(url) as response:
    response = await response.read()

I am having trouble repurposing it to a code that does not involve aiohttp.

Could anyone show me how to use a semaphore on the below example: (for instance having a sema = asyncio.Semaphore(2) that allows only 2 simultaneous computation of the factorial)?

import asyncio

async def factorial(name, number):
    f = 1
    for i in range(2, number+1):
        print("Task %s: Compute factorial(%s)..." % (name, i))
        await asyncio.sleep(1)
        f *= i
    print("Task %s: factorial(%s) = %s" % (name, number, f))

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(
    factorial("A", 2),
    factorial("B", 3),
    factorial("C", 4),
))
loop.close()

I tried

import asyncio

sema = asyncio.Semaphore(2)

async def factorial(name, number):
    async with sema:
        f = 1
        for i in range(2, number+1):
            print("Task %s: Compute factorial(%s)..." % (name, i))
            await asyncio.sleep(1)
            f *= i
        print("Task %s: factorial(%s) = %s" % (name, number, f))

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(
    factorial("A", 2),
    factorial("B", 3),
    factorial("C", 4),
))
loop.close()

I also tried the solution posted below as a comment. Both returns RuntimeError: Event loop is closed

jim jarnac
  • 4,804
  • 11
  • 51
  • 88
  • `with (await sema):` should ok? – stovfl Aug 28 '17 at 18:42
  • @stovfl no it does not work. I tried `async with sema:` and your suggestion - both return error `RuntimeError: Event loop is closed` – jim jarnac Aug 28 '17 at 21:14
  • Tried your Second Example, works as expected, only **two** simultaneous running `def factorial`. As `asyncio` changes with every Python Release tell which Python and OS Version you are using. I'm on Python 3.4.2 and Linux. – stovfl Aug 29 '17 at 09:03

0 Answers0