Sam
Sam

Reputation: 499

Thread starts without calling it's start method

I was going to ask another question when this one came to my mind. Please take a look at this piece of code:

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()

It creates a http server, serving files in the same directory as the script.
It works just OK but i can't understand why it works because I didn't use run() method when starting the thread,
was expecting to write something to call the run method, But it works just by starting the thread.
I would like to know why.
Thanks.
P.S: I'm using python 3.3 .

Upvotes: 2

Views: 99

Answers (1)

Noctua
Noctua

Reputation: 5218

The thing is, if you called the run method, you'd run that method in the same thread. The start method first creates a new thread, and then executes the run method in that thread. This way, the thread creation is abstracted away from you.

From the documentation of 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.

    """

Upvotes: 1

Related Questions