Confusion about multiprocess and asyncio in sanic

hi, dear. i have a confusion about multiprocess and asyncio in sanic.
below are simplified code , workers=2:

from sanic import Sanic
app = Sanic("test")

@app.get("/video_stream")
async def hello_world(request):
    response = await request.respond()
    await mjpeg(response)

async def mjpeg(response):
    ...
    # condition 2:  await asyncio.sleep(0.01)
    await response.write(...)
    
if __name__ == "__main__":
    app.run(workers=2)
  1. I try to open 4 video_stream:
    only 2 run successful respectively in (SpawnProcess-0,SpawnProcess-1) ,
    the other 2 video_stream are unreachable .

  2. I add await asyncio.sleep(0.01) in mjpeg and try to open 4 video_stream:
    all 4 video_stream will run successful , but all in one process !

how can i balance it?

That’s an OS level operation that Python does not control. Moreover, exactly how probably differs from OS to OS.

you are right , i run the same code in other computer . just come with different result

I have the same problem, actually, asyncio.sleep(0) can work. But this still increase additional CPU overhead.

sleep 0 almost always will cause cpu to jump because it makes your loop work infinitely hard. Try adding an offset and it should drop dramatically

I wrote a function to replace the sleep 0, and the function do nothing but interrupt the current task recklessly.

async def interrupt_events():
    @types.coroutine
    def linshi():
        yield

    await linshi()
    return

Can this called ‘offset’? :grinning:

:thinking:

What’s the question?

Sorry, lets forget the session here. I just make a reply to you in my topic. :grinning: