Non-blocking I/O with asyncio

前端 未结 3 606
小鲜肉
小鲜肉 2021-02-01 05:22

I\'m trying to write a networked game with Pygame and asyncio, but I can\'t work out how to avoid hanging on reads. Here is my code for the client:

@asyncio.coro         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 05:51

    You can "transform" a blocking task into a non-blocking one.

    I suggest this: https://docs.python.org/3/library/asyncio-eventloop.html#executor.

    I have a function that listens to a twitter feed, function "mention", and I run it in an executor, so if it hangs, it doesn't block the other tasks.

    @asyncio.coroutine
    def boucle_deux():
    #faire attendre la boucle si pas bcp de mots
        while True:
            print("debut du deux")
            value = t.next()
            future2 = loop.run_in_executor(None, mention, "LQNyL2xvt9OQMvje7jryaHkN8",
                                           "IRJX6S17K44t8oiVGCjrj6XCVKqGSX9ClfpGpfC467rajqePGb",
                                           "2693346740-km3Ufby8r9BbYpyzcqwiHhss22h4YkmnPN4LnLM",
                                           "53R8GAAncFJ1aHA1yJe1OICfjqUbqwcMR38wSqvbzsQMB", 23, value)
            response2 = yield from future2
            yield from asyncio.sleep(5)
            print("fin du deux")
    
    asyncio.Task(boucle_deux())
    

提交回复
热议问题