python threads - please explain <p>I'm trying to understand how threads work in python and I'm slightly confused around a few things. </p> <p>I was under the impression that you could run different tasks at the same time in parallel when using threads? </p> <p>The code below will demonstrate some of the issues I'm experiencing with threads. (I know there are better ways writing a port scanner but this will clarify the issues I'm having )</p> <p>============ Start Example ============</p> <pre><code> import socket import threading def test2(start,end): for i in range(int(start),int(end)): server = 'localhost' s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((server,i)) print("port", i , "is open", threading.current_thread().name) s.close() except socket.error as e: s.close() def threader(): print(threading.current_thread().name) if threading.current_thread().name == "Thread-0": test2(1,1000) elif threading.current_thread().name == "Thread-1": test2(1000,2000) elif threading.current_thread().name == "Thread-2": test2(2000,3000) elif threading.current_thread().name == "Thread-3": test2(3000,4000) for i in range(4): t = threading.Thread(target=threader, name= "Thread-"+str(i)) t.start() </code></pre> <p>============ End Example ============</p> <p>if I would scan 1000 ports with 1 thread it usually takes around 7-8 sec.</p> <p>The problem with the code above is that this takes around 30 sec to execute.</p> <p>Should it not take around 7-8 sec to execute if all threads are running in parallel and are scanning the same amount of ports? </p> <p>I'd really appreciate if someone could explain what I'm doing wrong here.</p> <p>TIA!</p>