Mar 25, 2020

Python thread lock release

#####
#If you don't use lock, sum will be not printed as 500000
#If you use lock, you get the sum as expected 500000 (5 threadsList, 100000 each)
#####

from threading import Thread
from threading import Lock
import sys

class CounterClass:
    def __init__(self):
        self.count = 0
        self.lock = Lock()

    def increment(self):
        for _ in range(100000):
            self.lock.acquire()
            self.count += 1
            self.lock.release()


if __name__ == "__main__":
   
    # Sets the thread switch interval
    sys.setswitchinterval(0.005)

    numThreads = 5
    threadsList = []
    counterObj = CounterClass()

    for i in range(0, numThreads):
        threadsList.append(Thread(target=counterObj.increment))

    for i in range(0, numThreads):
        threadsList[i].start()

    for i in range(0, numThreads):
        threadsList[i].join()

    if counterObj.count != 500000:
        print(" count = {0}".format(counterObj.count))
    else:
        print(" count = 500000")


No comments:

Post a Comment