import threading
from random import randint
from time import sleep
defprint_number(number):# Sleeps a random 1 to 10 seconds
rand_int_var = randint(1,10)
sleep(rand_int_var)print"Thread "+str(number)+" slept for "+str(rand_int_var)+" seconds"
thread_list =[]for i inrange(1,10):# Instantiates the thread# (i) does not make a sequence, so (i,)
t = threading.Thread(target=print_number, args=(i,))# Sticks the thread in a list so that it remains accessible
thread_list.append(t)# Starts threadsfor thread in thread_list:
thread.start()# This blocks the calling thread until the thread whose join() method is called is terminated.# From http://docs.python.org/2/library/threading.html#thread-objectsfor thread in thread_list:
thread.join()# Demonstrates that the main process waited for threads to completeprint"Done"
# Python program to illustrate the concept# of threading# importing the threading moduleimport threading
defprint_cube(num):"""
function to print cube of given num
"""print("Cube: {}".format(num * num * num))defprint_square(num):"""
function to print square of given num
"""print("Square: {}".format(num * num))if __name__ =="__main__":# creating thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))# starting thread 1
t1.start()# starting thread 2
t2.start()# wait until thread 1 is completely executed
t1.join()# wait until thread 2 is completely executed
t2.join()# both threads completely executedprint("Done!")
Using a with statement alongwith the lock ensures the mutual exclusion. By exclusion, it is meant that at a time only one thread (under with statement)is allowed to execute the block of a statement.
The lock for the duration of intended statements is acquired andis released when the control flow exits the indented block
A thread is a separate flow of execution. This means that your program will have two things happening at once. But for most Python 3 implementations the different threads do not actually execute at the same time: they merely appear to.