How to terminate this program of thread pool + queue (ThreadPoolExecutor+queue)?

the following test program is written when learning concurrency, and the function is to load data into queue 1 and load it into queue 2 after processing.

import time
from queue import Queue
from concurrent.futures import ThreadPoolExecutor

-sharp
q1 = Queue()
q2 = Queue()

-sharp 1:12
def worker1():
    while True:
        item = q1.get()
        print("get item from q1...", "item = %s" % item)
        time.sleep(0.1)
        q2.put(item ** 2)
        q1.task_done()

-sharp 2:2
def worker2():
    while True:
        item = q2.get()
        print("get item from q2...", "item = %s" % item)
        time.sleep(0.1)
        q2.task_done()

-sharp 
pool = ThreadPoolExecutor(10)
p1 = pool.submit(worker1)
p2 = pool.submit(worker2)

-sharp 1
for item in range(6):
    q1.put(item)

q1.join()
q2.join()
p1.result()
p2.result()

clipboard.png
the calculation program can output the expected results, but the program does not stop running. What is the reason and how to solve it?

Mar.07,2021

because while True is always in the two threads, you can add an end signal, for example, send a -1 to the queue, and if the thread receives it, exit the while loop. Note that both queues send an end signal.

Menu