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

3
  • with (await sema): should ok? Commented Aug 28, 2017 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 Commented Aug 28, 2017 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. Commented Aug 29, 2017 at 9:03

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.