每當你想同時做兩件事情,你需要併發。 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)
這類似於僱用廚房手幫助您切碎蔬菜,同時切碎蔬菜。你必須購買另一把刀和砧板,但是你應該能夠以這種方式將一半的土豆切碎。
來源
2017-09-15 19:57:06
wim
在單獨的線程中執行每種方法 – ingvar
您可以請給我看看。 –
什麼是'test2'和'test4'? – wim