gpt4 book ai didi

multithreading - 线程启动而不调用它的启动方法

转载 作者:行者123 更新时间:2023-12-03 13:04:55 24 4
gpt4 key购买 nike

当我想到这个问题时,我要问另一个问题。
请看一下这段代码:

import threading
from http.server import HTTPServer, SimpleHTTPRequestHandler
class Server(threading.Thread):
def __init__(self, name, address='127.0.0.1',port=8080):
threading.Thread.__init__(self, name=name)
self.address = address
self.port=port
HandlerClass = SimpleHTTPRequestHandler
ServerClass = HTTPServer
self.httpd = ServerClass((address, port), HandlerClass)

def run(self):
self.httpd.serve_forever()

def shutdown(self):
self.httpd.shutdown()
self.httpd.socket.close()

httpd_thread= Server("http",'127.0.0.1',30820)
httpd_thread.start()

它创建一个http服务器,在与脚本相同的目录中提供文件。
它工作正常,但是我不明白为什么会工作,因为启动线程时我没有使用run()方法,
本来希望写一些东西来调用run方法,但是它只是通过启动线程而起作用。
我想知道为什么。
谢谢。
附注:我正在使用python 3.3。

最佳答案

问题是,如果您调用了run方法,那么您将在同一线程中运行该方法。 start方法首先创建一个新线程,然后在该线程中执行run方法。这样,线程创建就可以从您那里抽象出来。

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 RuntimeError if called more than once on the
same thread object.

"""

关于multithreading - 线程启动而不调用它的启动方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20787753/

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