Programming python

A simple Python threading example

$ python –version
Python 2.7.3

import sys
import threading
import logging
import time

def setup_logging():
  logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

def call_me( ):
  t = threading.current_thread()
  id_str = str( t.ident )

  logging.debug( id_str )

for i in range( 10 ):
  print id_str , ' : ' , i
  time.sleep( 1 )

def main():
  for i in (1,2,3,4,5,6,7,8):

if __name__ == '__main__':
  sys.exit( main() )

$ time python

real 1m20.864s
user 0m0.080s
sys 0m0.048s

update main() and invoke call_me() in its own thread.

def main():
  for i in (1,2,3,4,5,6,7,8):
    t = threading.Thread( target=call_me )

$ time python
real 0m10.222s
user 0m0.076s
sys 0m0.044s

Notice the significant difference in the ‘real’ time ~ 70 secs.

In the first example the sequential calls to the call_me() method are blocking. Each successive call has to wait for the previous call to complete.

In the updated 2nd example which uses threading to invoke call_me() the invocations are not blocking and ready to execute without waiting for the previous calls to complete.

Also, once they are started some threads are working while the others are idle thus maximizing CPU usage.

Using multiple threads to divide and execute a large task or tasks that makes blocking calls saves time.

Leave a Reply

Your email address will not be published. Required fields are marked *