【问题标题】:Wait for Object initiated to return list and then continue等待对象启动返回列表,然后继续
【发布时间】:2015-01-25 11:15:37
【问题描述】:

我有一个主 python 脚本,它创建两个对象

obj1 = xmlobj()
list1, list2, list3 = obj1.parsexml("xmlfile")
//parsexml returns me three lists
obj2 = htmlobj()
str1 = obj2.createhtmltable(list1, list2, list3)
//creates a html table

但是,当我运行脚本时,主脚本不等待obj1.parsexml返回值,而是执行并立即进入下一个创建obj2的语句,因此甚至没有执行createhtmltable,因为list1,list2,list3没有返回其中的价值观。另外,parsexml 工作正常,没有任何错误

如何解决这个问题,谢谢

【问题讨论】:

  • 您需要使用输入和输出队列。一组线程应该从 task 队列中获取文件名/url,并将parsexml 的结果转储到 results 队列中。然后你的主线程可以从结果队列中读取并转换为 html 文件。
  • 当然,会尝试更新它
  • 您的描述没有意义。在调用obj1.parsexml("xmlfile") 之后,在此调用返回之前不会继续执行。如果您在该函数中启动线程,它们将独立运行,但这是一个不同的问题。

标签: python multithreading class


【解决方案1】:

这是一个例子:

import Queue  #python 3.x => import queue
import urllib2  #python 3.x => import urllib.request
import threading

urls = [
        "http://www.apple.com",
        "http://www.yahoo.com",
        "http://www.google.com",
        "http://www.espn.com",
]

def do_stuff():
    while True:
        url = task_q.get()

        if url == "NO_MORE_DATA":
            break

        data = urllib2.urlopen(url).read()[:200]
        results_q.put(data)

#Create the Queues:
task_q = Queue.Queue()
results_q = Queue.Queue()

num_worker_threads = 2

for i in range(num_worker_threads):
    t = threading.Thread(target=do_stuff)
    t.daemon = True  #daemon threads are killed when the main thread finishes
    t.start()  #All threads block because the task_q is empty.

#Add the tasks/urls to the task_q:
for url in urls:
    task_q.put(url)

#Like frantic dogs, all the threads are chomping on the task_q...

#Add a stop for each thread, so that after all the urls 
#have been removed from the task_q, the threads will terminate:
for i in range(num_worker_threads):   
    task_q.put("NO_MORE_DATA")  

results_count = len(urls)  #Need to know how many results are expected in order to know when to stop reading from the results_q

while True:
    result = results_q.get()

    #process the result here
    print result
    print '-' * 10

    results_count -= 1
    if results_count == 0:  #then all results have been processed, so you should stop trying to read from the results_q
        break

队列.join()
阻塞,直到队列中的所有项目都被获取并且 处理。

每当一个项目被添加到 队列。每当消费者线程调用时,计数就会下降 task_done() 表示该项目已被检索并对其进行所有工作 已经完成。当未完成任务的计数降至零时,join() 解锁。 https://docs.python.org/2.7/library/queue.html#module-Queue

是的,但谁愿意等到所有结果都已添加到结果队列中,然后再开始处理结果。为什么不尽快开始处理第一个结果?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2018-05-19
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    相关资源
    最近更新 更多