Python Race Condition

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Program 1

# Race Condition 
import time
from threading import *

l=Lock()
def printTable(n):
    l.acquire()
    for i in range(1,11):
        print(n*i)
        time.sleep(1)
    l.release()
    
#Main Thread
start=time.time()
T1=Thread(target=printTable,args=(5,),name="One")
T2=Thread(target=printTable,args=(8,),name="Two")
T3=Thread(target=printTable,args=(10,),name="Two")
T1.start()
T2.start()
T3.start()

T1.join()
T2.join()
T3.join()
end=time.time()
print(end-start)

print("-----------Main End Here--------")

Program 2

# Lock using OOPs
import time
from threading import *

# Outer resource 
l=Lock()
class Table:
    def printTable(self,n):
        l.acquire()
        for i in range(1,11):
            print(n*i)
            time.sleep(1)
        l.release()

class MyThread1(Thread):
    def run(self):
        T1=Table()
        T1.printTable(5)

class MyThread2(Thread):
    def run(self):
        T1=Table()
        T1.printTable(8)

#Main Thread
start=time.time()
M1=MyThread1()
M2=MyThread2()
M1.start()
M2.start()
M1.join()
M2.join()
print("------Main Thread Ends-------")
end=time.time()
print(end-start)

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

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