简体   繁体   中英

How can I make self-contained async functions that doesn't stop in Python?

I'm trying to make a self-contained async function inside a loop in Python. The idea is to have a loop that iterates over the functions, one to get information (let's call it "FunctionA") and the other to process it ("FunctionB"). The FunctionB usually takes some time to work and at that time the FunctionA doesn't get any information, so I decided to make FunctionB asynchronous. In simplified form this is my function:

 async def main():
        while(True):
            data = functionA()
            if (data):
                task = asyncio.create_task(functionB(data))
            await task
asyncio.run(main())

The problem is the last await. If I don't use it the function main restarts the FunctionB at each turn of the loop, but if I use it the code has to wait for FunctionB and I have the same timing issue as I don't use asynchronous functions. How could I make it? Is there another methods to get it?

What you are describing is the "Producer-consumer design pattern" , where functionA() is the Producer and functionB() is the Consumer .

here you can find a tutorial with code examples that can help you implement what you are trying to achieve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM