2as*_*asy 5 python multithreading loops
我刚开始学习多线程,我有一个关于应用循环的问题。
如下面的代码所示,我正在尝试运行多线程,直到 self.llist 的长度超过 10。
下面的代码工作正常,但我不确定这是否是循环运行的有效方式。
import threading
class aa:
def __init__(self):
self.llist = []
def task1(self):
self.llist.append('task1')
def task2(self):
self.llist.append('task2')
def main(self):
while len(self.llist) < 10:
t1 = threading.Thread(target=self.task1, name='t1')
t2 = threading.Thread(target=self.task2, name='t2')
t1.start()
t2.start()
t1.join()
t2.join()
aa().main()
Run Code Online (Sandbox Code Playgroud)
小智 0
我尝试使用并发.futures 并发现您的执行时间少于 ThreadPoolExecutor 实现。这是代码:
from concurrent.futures import ThreadPoolExecutor
from time import time
class aa:
def __init__(self):
self.llist = []
def task(self, name):
self.llist.append(name)
def main(self):
while len(self.llist) < 10:
with ThreadPoolExecutor(2) as execute:
thread_name = ['t1', 't2']
execute.map(self.task, thread_name)
print(self.llist)
start = time()
aa().main()
print(time()-start)
Run Code Online (Sandbox Code Playgroud)