alf*_*eza 3 python multithreading control-flow
我已经遇到了一些使用线程模块管理线程的例子(使用Python 2.6).
我想要了解的是这个例子如何调用"run"方法以及在哪里.我什么都看不到.ThreadUrl类在main()函数中实例化为"t",这是我通常期望代码启动"run"方法的地方.
也许这不是使用线程的首选方式?请赐教:
#!/usr/bin/env python
import Queue
import time
import urllib2
import threading
import datetime
hosts = ["http://example.com/", "http://www.google.com"]
queue = Queue.Queue()
class ThreadUrl(threading.Thread):
"""Threaded Url Grab"""
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
#grabs host from queue
host = self.queue.get()
#grabs urls of hosts and prints first 1024 bytes of page
url = urllib2.urlopen(host)
print url.read(10)
#signals to queue job is done
self.queue.task_done()
start = time.time()
def main():
#spawn a pool of threads, and pass them queue instance
for i in range(1):
t = ThreadUrl(queue)
t.setDaemon(True)
t.start()
for host in hosts:
queue.put(host)
queue.join()
main()
print "Elapsed time: %s" % (time.time() - start)
Run Code Online (Sandbox Code Playgroud)
按照pydoc:
Thread.start()启动线程的活动.
每个线程对象最多只能调用一次.它安排在一个单独的控制线程中调用对象的run()方法.
如果在同一个线程对象上多次调用,此方法将引发RuntimeException.
思考python Thread对象的方法是它们采用一些同步写入的python代码(在run方法中或通过target参数)并将其包装在知道如何使其异步运行的C代码中.这样做的好处在于你可以start像对待一种不透明的方法一样对待:除非你用C语言重写这个类,否则你没有任何业务覆盖它,但你可以run非常具体地对待它.例如,如果要同步测试线程的逻辑,这可能很有用.您只需要调用t.run()它,它将像任何其他方法一样执行.