gpt4 book ai didi

python - 附加以列出线程的结果

转载 作者:行者123 更新时间:2023-11-28 18:13:12 25 4
gpt4 key购买 nike

这是我的代码:

import threading

def worker(num):
"""thread worker function"""
print '{Worker: %s}' % num
return

threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
print(threads)

这是上面代码的结果:

{Worker: 0}
{Worker: 1}
{Worker: 2}
{Worker: 3}
{Worker: 4}
[<Thread(Thread-1, stopped 17204)>, <Thread(Thread-2, stopped 852)>, <Thread(Thread-3, stopped 17092)>, <Thread(Thread-4, stopped 10632)>, <Thread(Thread-5, stopped 2396)>]

我如何将这些结果附加到列表中并创建一个类似这样的列表:

[[{Worker: 0}],[{Worker: 1}],[{Worker: 2}],[{Worker: 3}],[{Worker: 4}]]

已编辑: 实际上我的 def 包含一个请求 REST 方法,它消耗了几秒钟,经过一些尝试我发现线程不等待获取结果而不是填充数组列表,然后我将我的代码改造成一个为你模拟的字符串变量,在这种情况下,我在 def 的第一行放了一个 time.sleep(1) 然后运行线程,它有一个空列表....我将 sleep 时间减少到 0.001 直到得到结果和线程工作和数组已填充。

import threading

def worker(txt):
"""thread worker function"""
if txt != '[{}]':
time.sleep(0.01) # this time has empty result till replace with 0.001 or lesser
lst.append(['{Worker: %s}' % txt])
# time.sleep(5)
return


xx = ['abc','def','ghi','jkl','mno','pqr','stw','xyz']

threads, lst = [], []
for i in xx:
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
# t.join()
print(lst) #[['{Worker: abc}'], ['{Worker: jkl}'], ['{Worker: ghi}'], ['{Worker: def}']] for 0.001 sleep time
# print(threads)

最佳答案

你的意思是这样的吗?

import threading

def worker(num):
"""thread worker function"""
lst.append(['{Worker: %s}' % num])
return

threads, lst = [], []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
print(lst)
#print(threads)

# [['{Worker: 0}'], ['{Worker: 1}'], ['{Worker: 2}'], ['{Worker: 3}'], ['{Worker: 4}']]

关于python - 附加以列出线程的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49999993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com