Search code examples
pythonpython-3.xmultithreadingpython-requestssleep

Will another thread execute while another thread waits for an HTTP response?


So I just finished watching this video on youtube. To my understanding while one thread sleeps, other threads in a program can run. My question is, is waiting for a HTTP response considered "sleeping" ? And will other tasks execute while waiting for a response?

For example:

from threading import Thread
from requests import get

def send_request():
    response = get('https://www.google.com/')
    return response

def add(x):
    return x + 2

t1 = Thread(target=send_request)
# t1.start()
t2 = Thread(target=add, args=(1,))
# t2.start()
t3 = Thread(target=add, args=(3,))
# t3.start()

t1.start()
t2.start()
t3.start()

Let's say it takes 100 milliseconds to get a response from get('https://www.google.com/') will t1 and t2 execute within the 100 milliseconds to get a response? What difference does it make when I call .start() on each thread object after ALL are instantiated oppose to calling .start() after EACH instantiation?

Thanks for all of those who reply in advance!


Solution

  • Is waiting for a HTTP response considered "sleeping"?

    Waiting for the HTTP response is slow, and the CPU will most likely switch to run the other threads before the response is available. So the answer is yes.

    Will other tasks execute while waiting for a response?

    Yes. If you place a print statement inside the add and send_request functions, you'll see that the add will print its output before send_request.

    What difference does it make when I call .start() on each thread object after ALL are instantiated oppose to calling .start() after EACH instantiation?

    There is practically no difference. When a thread is started (using start()), it is set to run concurrently with the main program's thread. The main thread can start other threads too, and they will run concurrently as well.