Python 3 线程,队列
Python 3 threading , queue
我遇到了一个关于从线程向 queue.Queue 添加数据的“小”问题。
环境数据:Ubuntu18.04/Python3.6.7/Python3.8.5
在下面的行中,我将 post 我的简化代码。任何帮助将不胜感激。
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))
我的第二次调用将 return 一个空列表。请给我一个想法。
问题出在“thread = None”之后,第一次在线程上执行该方法后附加了一个 并在第二次调用时验证
“如果线程是 None”,则 suprize 不是 None。
我遇到了一个关于从线程向 queue.Queue 添加数据的“小”问题。
环境数据:Ubuntu18.04/Python3.6.7/Python3.8.5
在下面的行中,我将 post 我的简化代码。任何帮助将不胜感激。
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))
我的第二次调用将 return 一个空列表。请给我一个想法。
问题出在“thread = None”之后,第一次在线程上执行该方法后附加了一个