运行无限循环的两个类
问题描述:
我有两个类都有for循环永远持续下去。当创建一个超级,我无法获得类第二次运行,由于类FIrst也循环。这里有一些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有几个选项内置的同时做几件事情:
使用协同程序
这有时被称为合作多任务。并发性在主线程中全部实现。
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,并且是这里唯一的解决方案,可以实现真正的并行,所以这种方法通常是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)
这类似于雇用厨房手帮助您切碎蔬菜,同时切碎蔬菜。你必须购买另一把刀和砧板,但是你应该能够以这种方式将一半的土豆切碎。
在单独的线程中执行每种方法 – ingvar
您可以请给我看看。 –
什么是'test2'和'test4'? – wim