Thread Synchronization-

    • – When two threads are trying to execute the same function at a same time then to handle this situation thread will comes in picture and thread handle this by allowing the function access sequentially and this process is know as Thread Synchronization.

 

  • Lock-

  • – With the help of Lock class we can implement the Thread Synchronization.
  • – When we implement the lock concept then if function is trying to access by more than one thread then 2nd thread has to wait until the 1st thread execution will not complete.

Ex-

from threading import Thread, Lock
class Demo:
    data=0
    lock = Lock()
    def add():
        Demo.lock.acquire()
        Demo.data= Demo.data+1
        Demo.lock.release()

class child1(Thread):
    def run(self):
        for x in range(7):
            Demo.add()

class child2(Thread):
    def run(self):
        for y in range(7):
            Demo.add()
class Test:
    def main():
        obj1 = child1()
        obj2 = child2()
        obj1.start()
        obj2.start()
        #obj1.join()
        #obj2.join()
        print("Final data-", Demo.data)
Test.main()

Output-
	Final data- 14
Menu