如何同时运行具有异步函数的类的多个实例?

问题描述 投票:0回答:1
class calculation():
    def __init__(self, value):
        self.value = value

    async def one(self):
        while True:
            print(self.value * 1)
            await asyncio.sleep(1)

    async def two(self):
        while True:
            print(self.value * 2)
            await asyncio.sleep(1)

    async def starter(self):
        await asyncio.gather(self.one(), self.two())
           

if __name__ == '__main__':
    
    a = calculation(2)
    b = calculation(3)
   
    p1 = multiprocessing.Process(target=asyncio.run(a.starter()))
    p2 = multiprocessing.Process(target=asyncio.run(b.starter()))
    p1.start()
    p2.start()

我尝试运行上面的代码,但只有第一个实例(a)运行,(b)被阻止运行,是否可以同时运行两个实例,谢谢。

python multiprocessing python-asyncio
1个回答
0
投票

您可以使用

threading

import asyncio
import threading


class Calculation:
    def __init__(self, value):
        self.value = value
        self.running = True

    async def one(self):
        while self.running:
            print(self.value * 1, 'one')
            await asyncio.sleep(1)

    async def two(self):
        while self.running:
            print(self.value * 2, 'two')
            await asyncio.sleep(1)

    async def starter(self):
        task1 = asyncio.create_task(self.one())
        task2 = asyncio.create_task(self.two())
        await asyncio.gather(task1, task2)

    def stop(self):
        self.running = False


def run_calculation(calculation_instance):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(calculation_instance.starter())
    loop.close()


if __name__ == '__main__':
    a, b = Calculation(2), Calculation(3)

    t1 = threading.Thread(target=run_calculation, args=(a,))
    t2 = threading.Thread(target=run_calculation, args=(b,))
    t1.start()
    t2.start()

    t1.join(timeout=1)
    t2.join(timeout=1)

    a.stop()
    b.stop()

打印

2 one
4 two
3 one
6 two
2 one
4 two
3 one
6 two
2 one
4 two
3 one
6 two
© www.soinside.com 2019 - 2024. All rights reserved.