Python Multithreading basics confusion
<p>I have the below code:</p>

<pre><code>import time
from threading import Thread

def fun1():
 time.sleep(5)

def fun2():
 time.sleep(5)

def fun3():
 time.sleep(5)

def fun4():
 time.sleep(5)

if __name__ == '__main__':
  t1 = Thread(target=fun1, args=())
  t2 = Thread(target=fun2, args=())
  t3 = Thread(target=fun3, args=())
  t4 = Thread(target=fun4, args=())
  t1.start()
  t2.start() 
  t3.start() 
  t4.start()
  start = time.clock()
  t1.join()
  t2.join()
  t3.join()
  t4.join()
  end = time.clock()
  print("Time Taken = ",end-start)
</code></pre>

<p>Que1: <strong>At a time only one thread will be serviced</strong>, meaning if the control is with thread t1,rest other threads will be waiting. Once the context switch takes place to thread t2,rest all other threads(t1,t3 and t4) will be waiting.
Is that the correct understanding?</p>

<p>Que2:If my understanding of Que1 is true, the total time(start - end) should be twenty seconds(as good as running in sequential manner rather than threaded manner)...but it is somewhat close to 5 seconds....why?At the end of the day,the threads are getting executed in sequence(though, not in entirety) one by one 
Please explain in laymen terms.Where is my understanding incorrect?</p>

<p>Que3:What if i do the same thing using multiprocessing?How will the execution differ?  </p>

<p>Que4:Let's say(assume) fun1() has the code that does a 1000 repeat count ping  to Router 1 and takes a time of 1 min.
Similary, fun2() does a 1000 repeat count ping  to Router 2 and takes a time of 1 min.
Similary, fun3() does a 1000 repeat count ping  to Router 3 and takes a time of 1 min.</p>

<p>If i do this sequentially, total expected time is 3 min for(ping to R1,then ping to R2 and then ping to R3)
But when i did this using threading,the total execution time was almost close to 1 min. Why ? I am unable to understand.</p>

<p>For multithreading environment in python. We have two very different kind of taks:</p>

<ul>
<li>CPU bound: like adding number, running for loop ... any activities that consume CPU. This kind of task hold GIL so it prevent other thread running.</li>
<li>not CPU bound (may be waiting for IO activities from outside resource like network ...):sleep system call does not use CPU so it's in this kind. this kind releases GIL while it waits for IO, sleep timeout .. so other thread can take lock and running.
That is why your program take around 5 seconds because all of your threads can run in parallel.</li>
</ul>

python multithreading multiprocessing python-2.x gil