Python 3多线程,线程返回并行运行

时间:2017-03-10 17:02:24

标签: multithreading python-3.x

我正在尝试运行以下线程代码。

import Queue
import threading

def get_items(url):
    print(url)
    #Do some stuff with print here
    return url.split()

q = Queue.Queue()
urls = [LIST OF URLS]

for u in urls[:10]:
    t = threading.Thread(target=get_items, args=(q, u))
    t.daemon = True
    t.start()
    t.join()

这应该并行运行线程,但它是按顺序运行的。其次,如何在列表中附加thread的return语句的值。?

1 个答案:

答案 0 :(得分:0)

当我对其进行了以下更改时,我的代码成功运行。

import Queue
import threading

def get_items(q, url):
    print(url)
    #Do some stuff with print here
    q.put(url.split())

q = Queue.Queue()
urls = [LIST OF URLS]

for u in urls[:10]:
    t = threading.Thread(target=get_items, args=(q, u))
    t.daemon = True
    t.start()
    th.append(t)

for t in th:
    t.join()

print(q.get())