多线程,线程完成后立即开始而无需等待

时间:2019-05-15 01:01:20

标签: python multithreading

所以我才刚刚开始学习python线程,想知道我可以在线程完成后立即启动一个线程,而无需等待另一个线程。我在下面编写了一个简单的代码来测试每个线程将在哪里执行10次。

def thread_func(id):
    logging.info("Thread {} is starting at {}".format(id, datetime.now().time()))
    if id == 0:
        time.sleep(1)
        logging.info("Thread {} ends at {}".format(id, datetime.now().time()))
    elif id == 1:
        time.sleep(3)
        logging.info("Thread {} ends at {}".format(id, datetime.now().time()))
    elif id == 2:
        time.sleep(5)
        logging.info("Thread {} ends at {}".format(id, datetime.now().time()))

for i in range(10):
    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
        executor.map(thread_func, range(3))

在这种情况下,线程1、2和3将同时运行,但线程3完成后线程1将再次启动。我希望线程1在完成后立即启动,并且与线程2和3相同。

edit:感谢迈克尔,此解决方案得以解决!下面是更新的代码

def thread_func(id):
    for i in range(3):
        logging.info("Thread {} is starting at {}".format(id, datetime.now().time()))
        if id == 0:
            time.sleep(1)       
        elif id == 1:
            time.sleep(3)
        elif id == 2:
            time.sleep(5)
        logging.info("Thread {} ends at {}".format(id, datetime.now().time()))

with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
    executor.map(thread_func, range(3))

0 个答案:

没有答案