追加列出线程的结果

时间:2018-04-24 10:59:23

标签: python python-multithreading

这是我的代码:

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方法,它消耗了几秒钟,经过一些尝试我发现线程不等待获得结果而不是填充数组列表,然后我将我的代码改为一个字符串变量来模拟你,在这种情况下我把一个time.sleep(1)放在def的第一行然后运行线程,它有一个空列表....我的睡眠时间减少到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)

1 个答案:

答案 0 :(得分:1)

你的意思是这样吗?

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}']]