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>Blocking calls in Python (<code>sleep</code>, waiting on I/O or locks) release the GIL, allowing other threads to run while they are blocked, so all four threads can <code>sleep</code> in parallel, that's why you're seeing a five second delay. If you want to see the effects of GIL contention, have the thread function do something CPU bound, e.g.</p>

<pre><code>def fun():
    for _ in xrange(1000000000):
        pass
</code></pre>

<p><code>multiprocessing</code> won't change a thing for the <code>sleep</code> case, since you're not GIL bound, but it would improve the wall clock time of the CPU bound case if you have more than one core to run on.</p>

python multithreading multiprocessing python-2.x gil