我尝试从链接获取数据(使用urllib)并按顺序打印(首先从第一个链接获取数据,从第二个链接获取数据等等)。当然,没有运行良好的线程并打印它按照正确的顺序,但当我使用线程时,它会破坏顺序,无法弄清楚如何修复它 这是我的代码:谢谢!!
def with_threading():
def run(num, q):
q.put(urllib2.urlopen("%s" % str(num)).read())
start_time = time.time()
q = Queue.Queue()
movies_names_list = []
threads_list = [threading.Thread(target=run, args=(i, q)) for i in xrange(1, 33)]
for thread in threads_list:
thread.start()
for thread in threads_list:
thread.join()
for i in xrange(1, 33):
movies_names_list.append(q.get())
print movies_names_list
print "\nElapsed Time: %s" % (time.time() - start_time)
答案 0 :(得分:1)
您可以通过在将每个影片放入队列之前用附加索引标记每个影片然后对结果进行排序来实现它:
def with_threading():
def run(num, q):
q.put(((urllib2.urlopen("%s" % str(num)).read()), num))
start_time = time.time()
q = Queue.Queue()
movies_names_list = []
threads_list = [threading.Thread(target=run, args=(i, q)) for i in xrange(1, 33)]
for thread in threads_list:
thread.start()
for thread in threads_list:
thread.join()
for i in xrange(1, 33):
movies_names_list.append(q.get())
res = sorted(movies_names_list, key=lambda tup: tup[1])
res = [item[0] for item in res]
print res
print "\nElapsed Time: %s" % (time.time() - start_time)