【问题标题】:Python 3 threading , queuePython 3 线程,队列
【发布时间】:2021-01-08 07:50:15
【问题描述】:

我正面临一个“小”问题,即从线程向 queue.Queue 添加数据。

环境数据:Ubuntu 18.04 / Python 3.6.7 / Python 3.8.5

在下面的行中,我将发布我的简化代码。任何帮助将不胜感激。

from threading import Thread,Lock
from queue  import Queue
from random import randint

thread = None
thread_lock = Lock()
q = Queue()


def worker(number):
    random_number= [str(randint(1,999)),number]
    q.put(random_number)


def first_function(iteration):
    global thread
    some_list=[]
    with thread_lock:
        threads=[]
        if thread is None:
            for iterator in range(iteration):
                thread = Thread(target=worker,args=(iterator,))
                threads.append(thread)
                thread.start()
        for thread_ in threads:
            thread_.join()
        thread = None
    while not q.empty():
        some_list.append(q.get())
    return (some_list)    

print(first_function(10))
print(first_function(5))

我的第二次调用将返回一个空列表。请给我一个想法。

【问题讨论】:

    标签: python-3.x queue python-multithreading


    【解决方案1】:

    问题出在第一次在线程上执行该方法后的“thread = None”是附加一个 并在您验证时第二次调用 “如果线程是无”,惊喜不是无。

    【讨论】: