[英]Running Two classes for infinite for loops
我有两个类都有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)
这类似于雇用厨房的手来帮助你在砍菜时切碎蔬菜。 你必须买另一把刀和砧板,但你应该可以用这种方式将土豆切成两半。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.