Auto AdSense

Saturday, 24 January 2015

Python Multithreaded Programming






  • Starting a New Thread
    #!/usr/bin/python

    import thread
    import time

    # Define a function for the thread
    def print_time( threadName, delay):
       count = 0
       while count < 5:
         time.sleep(delay)
         count += 1
         print "%s: %s" % ( threadName, time.ctime(time.time()) )

    # Create two threads as follows
    try:
       thread.start_new_thread( print_time, ("Thread-1", 2, ) )
       thread.start_new_thread( print_time, ("Thread-2", 4, ) )
    except:
       print "Error: unable to start thread"

    while 1:
       pass
  • Output
    Thread-1: Thu Jan 22 15:42:17 2009
    Thread-1: Thu Jan 22 15:42:19 2009
    Thread-2: Thu Jan 22 15:42:19 2009
    Thread-1: Thu Jan 22 15:42:21 2009
    Thread-2: Thu Jan 22 15:42:23 2009
    Thread-1: Thu Jan 22 15:42:23 2009
    Thread-1: Thu Jan 22 15:42:25 2009
    Thread-2: Thu Jan 22 15:42:27 2009
    Thread-2: Thu Jan 22 15:42:31 2009
    Thread-2: Thu Jan 22 15:42:35 2009

No comments:

Post a Comment