python – threading.Thread中的流控制
作者:互联网
我已经遇到了一些使用线程模块管理线程的例子(使用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)
解决方法:
按pydoc:
Thread.start()
Start the thread’s activity.
It must be called at most once per thread object. It arranges for the
object’s run() method to be invoked in
a separate thread of control.This method will raise a RuntimeException if called more than
once on the same thread object.
思考python Thread对象的方法是它们采用一些同步编写的python代码(在run方法或通过target参数)并将其包装在知道如何使其异步运行的C代码中.这样做的好处在于你可以像对待一个不透明的方法一样对待开始:除非你用C语言重写类,否则你没有任何业务覆盖它,但你可以非常具体地对待它.例如,如果要同步测试线程的逻辑,这可能很有用.你需要的只是调用t.run(),它将像任何其他方法一样执行.
标签:python,multithreading,control-flow 来源: https://codeday.me/bug/20190717/1485204.html