如何在Python中将循环应用于多线程

时间:2019-12-17 07:32:59

标签: 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()

1 个答案:

答案 0 :(得分:0)

我尝试了current.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)