gpt4 book ai didi

python - threading.Thread 中的流控制

转载 作者:太空宇宙 更新时间:2023-11-03 12:35:22 31 4
gpt4 key购买 nike

我遇到了一些使用线程模块(使用 Python 2.6)管理线程的示例。

我想了解的是这个例子是如何调用“运行”方法的,在哪里调用的。我在任何地方都看不到它。 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 代码中。这样做的美妙之处在于,您可以将 start 视为一个不透明的方法:除非您用 C 重写该类,否则您没有任何业务可以覆盖它,但您可以将 视为非常具体地运行。例如,如果您想同步测试线程的逻辑,这会很有用。您只需调用 t.run(),它将像任何其他方法一样执行。

关于python - threading.Thread 中的流控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1454941/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com