Python threading for dummies

  • 0
Below an example I did for my office mate who wants to get his python code to run on several cores.
Pretty usefull for those who are just starting threads.


@author: Ricardo Leal
import time
import threading
from datetime import datetime

# Lock
lock = threading.Lock()

def myfunc(i):
    ''' Function to be threaded '''
    print "Tread %d is doing NON critical stuff" % i
    print "Tread %d is doing critical stuff"% i
    print "Tread %d has finished doing critical stuff" % i 

if __name__ == '__main__':
    t_start =    
    thread_list = []

    for i in range(10):
        print "Launching thread: ", i
        t = threading.Thread(target=myfunc, args=(i,))
        # Put threads in a list        
        # optional (rather than putting them on a list)
        # t.start()
    # Start all threads
    [x.start() for x in thread_list]

    print "Waiting for the threads to do their job!"
    # Wait for all of them to finish
    [x.join() for x in thread_list]
    print "Main: I haved waited for the threads to finish!"    
    t_end =
    t_total = t_end - t_start
    print "Total time: ", t_total
    print "Main has finished!"

No comments:

Post a Comment