The number of Python multithreaded queue elements is greater than the number of threads. Cannot exit.

read this question and answer python multithreading cannot exit? , a problem has been found that you will exit only when the number of elements in the queue is the same as the number of threads, and if the number of elements in the queue is greater than the number of threads, you will not be able to exit.
what should I do in this situation first?

import Queue
import threading

def basic_worker(queue):
    """
    
    """
    while True:
        try:
            item = queue.get(True,1)
        except :
            queue.task_done()
            break
        print("[%s]get %d"%(threading.current_thread(),item))
        -sharpqueue.task_done()


def basic():
    """
    4
    """
    print "start"
    queue = Queue.Queue()
    for i in range(4):
        t = threading.Thread(target=basic_worker, args=(queue,))
        t.start()
    for item in range(8):
        queue.put(item)
    queue.join()       -sharp block until all tasks are done
    print "got here"

if __name__ == "__main__":
    basic()

Nov.17,2021

If a join () is currently blocking, it will resume when all items have been processed (meaning that a task_done () call was received for every item that had been put () into the queue).

change the location of the task_done call.

import Queue
import threading


def basic_worker(queue):
    while True:
        try:
            item = queue.get(True, 1)
            queue.task_done()
            print('[%s]get %d' % (threading.current_thread(), item))
        except :
            break


def basic():
    print 'start'
    queue = Queue.Queue()
    for i in range(4):
        t = threading.Thread(target=basic_worker, args=(queue,))
        t.start()
    for item in range(8):
        queue.put(item)
    queue.join()       -sharp block until all tasks are done
    print 'got here'


if __name__ == '__main__':
    basic()
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b40936-2c517.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b40936-2c517.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?