Home > OS >  In python is the .start() command blocking for the time it takes the thread start to complete?
In python is the .start() command blocking for the time it takes the thread start to complete?

Time:12-11

Hypothesis: thread....start() blocks until start completes.
Question: Is hypothesis True or False?

Start http web server then open browser has the following code.

import sys
import time
import threading
import webbrowser
from http.server import HTTPServer, SimpleHTTPRequestHandler

ip = "127.0.0.1"
port = 3600
url = f"http://{ip}:{port}"


def start_server():
    server_address = (ip, port)
    httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
    httpd.serve_forever()


threading.Thread(target=start_server).start()
webbrowser.open_new(url)

while True: # make a blocker to prevent the application finish of execute:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        sys.exit(0)

This works fine. However, the following also works.

import sys
import time
import threading
import webbrowser
from http.server import HTTPServer, SimpleHTTPRequestHandler

ip = "127.0.0.1"
port = 3600
url = f"http://{ip}:{port}"


def start_server():
    server_address = (ip, port)
    httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
    httpd.serve_forever()


threading.Thread(target=start_server).start()
webbrowser.open_new(url)

Hypothesis: thread....start() actually blocks until start completes. So,webbrowser.open_new(url) does not execute until start completes. Thus making the following unnecessary.

while True: # make a blocker to prevent the application finish of execute:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        sys.exit(0)

I have not been able to prove or disprove the Hypothesis after extensive searching.

CodePudding user response:

There is no blocking when calling Thread.start() in the way you suggest. The call is blocking in the sense that a call is placed that initalizes the new-thread internal state, and a system call is made to start the actual OS Thread - but that should take less than 1ms. The function that is the target of the thread is only called on the new thread, and the main thread will continue to run, regardless of what takes place inside that function.

If you want your program not to end, there is no need to resort to a complicated pausing loop like the one you setup - just place a call to threading.join() instead. This will block until all other threads end running, and only them the threading calling join() will proceed.

  • Related