Python – A simple example using threading module

Example 1: Threading example which loops 10 times by also creating threads for the function. This script however, does not ensure that threads are being closed.

import threading
import time

def somefunction():
    for loop in range (10):
        print "thread sleeps for 10 seconds"
        time.sleep(10)
        print "thread woke up"

for counter in range(10):
     threader = threading.Thread(target=somefunction)
     threader.start()

Example 2: The script below is the same as the one above. However it employs threading accounting by storing each thread to a list. This allows to close threads when the process exits.

import threading
import time

def somefunction():
    for loop in range (10):
        print "thread sleeps for 20 seconds"
        time.sleep(20)
        print "thread woke up"

threads = []
num_threads = 10
for i in range(num_threads):
     # here you need to pass in "somefunction" without parens
     threads.append(threading.Thread(target=somefunction))
     threads[-1].start()

# then you need to join them (join waits for threads to finish)
for thread in threads:
    thread.join()
Share Button

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.