为无限循环运行两个类



我有两个类别的循环,它们永远存在。创建超级时,由于课程首次循环,我无法获得第二堂课。这是一些sudo代码。我失去了如何执行两者的操作,并且必须同时运行。

class First:
    def one(self):
        for test1 in test2:
            # go on forever
            print('here is 2')

class Second:
    def two(self):
        for test3 in test4:
            # go on forever
            print('here is 2')

class SuperNumber(First, Second):
    pass

Foo = SuperNumber()
Foo.one()
Foo.two()

每当您想一次做两件事时,都需要并发。Python有几个内置的选项,可以一次完成几件事:

使用Coroutines

这有时称为合作多任务。并发全部在主线程中实现。

import asyncio
class First:
    async def one(self):
        while True:
            print('here is 1')
            await asyncio.sleep(0)
class Second:
    async def two(self):
        while True:
            print('here is 2')
            await asyncio.sleep(0)
class SuperNumber(First, Second):
    pass
foo = SuperNumber()
one = foo.one()
two = foo.two()
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(one, two))

这类似于进行两次对话,一个人在电话上,另一个人面对面,请定期要求每个人暂时抓住片刻。

使用螺纹

这使用多个线程,但仍然只有一个CPU。最适合我们可以从gil的发布中受益的情况,例如IO结合的应用程序。

from concurrent.futures import ThreadPoolExecutor    
class First:
    def one(self):
        while True:
            print('here is 1')
class Second:
    def two(self):
        while True:
            print('here is 2')
class SuperNumber(First, Second):
    pass
foo = SuperNumber()
with ThreadPoolExecutor(max_workers=2) as executor:
    executor.submit(foo.one)
    executor.submit(foo.two)

这类似于您在烹饪晚餐时,然后将水放在炉子上,然后在等待水煮沸时切碎一些蔬菜。您[用户]不必只坐在那里看水沸腾,因为那是炉子[内核]工作,因此您可以同时使自己有用。

使用多处理

这使用了多个CPU,并且是可以实现True 并行性的唯一解决方案,因此此方法通常是CPU结合应用程序的最佳方法。请注意,代码与线程示例完全相同,但仅使用其他执行程序类。它的开销最多;您需要一个Python解释器,因此将其扩展到多个任务更为昂贵。

from concurrent.futures import ProcessPoolExecutor
class First:
    def one(self):
        while True:
            print('here is 1')
class Second:
    def two(self):
        while True:
            print('here is 2')
class SuperNumber(First, Second):
    pass
foo = SuperNumber()
with ProcessPoolExecutor(max_workers=2) as executor:
    executor.submit(foo.one)
    executor.submit(foo.two)

这类似于雇用厨房手,以帮助您在切碎蔬菜时切碎蔬菜。您必须购买另一把刀和切碎的板,但是您应该能够以这种方式将土豆切成一半的时间。

最新更新