Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I'm attempting to comprehend the fundamentals of threading and concurrency. I need a straightforward situation where two strings consistently attempt to get to one shared asset. 

The code:

import threading

class Thread(threading.Thread):

    def __init__(self, t, *args):

        threading.Thread.__init__(self, target=t, args=args)

        self.start()

count = 0

lock = threading.Lock()

def incre():

    global count 

    lock.acquire()

    try:

        count += 1    

    finally:

        lock.release()

def bye():

    while True:

        incre()

def hello_there():

    while True:

        incre()

def main():    

    hello = Thread(hello_there)

    goodbye = Thread(bye)

    while True:

        print count

if __name__ == '__main__':

    main()

Thus, I have two strings, both attempting to increase the counter. I believed that if string 'A' called incre(), the lock would be set up, forestalling 'B' from getting to until 'A' has delivered

Can anyone tell me, how does it exactly was the lock object used?

1 Answer

0 votes
by (26.4k points)

You can see that your locks are practically filling in as you are utilizing them, in the event that you hinder the cycle and make them block a smidgen more. You had the correct thought, where you encompass basic bits of code with the lock. Here is a little acclimation to your guide to show you how each looks out for the other to deliver the lock.

import threading

import time

import inspect

class Thread(threading.Thread):

    def __init__(self, t, *args):

        threading.Thread.__init__(self, target=t, args=args)

        self.start()

count = 0

lock = threading.Lock()

def incre():

    global count

    caller = inspect.getouterframes(inspect.currentframe())[1][3]

    print "Inside %s()" % caller

    print "Acquiring lock"

    with lock:

        print "Lock Acquired"

        count += 1  

        time.sleep(2)  

def bye():

    while count < 5:

        incre()

def hello_there():

    while count < 5:

        incre()

def main():    

    hello = Thread(hello_there)

    goodbye = Thread(bye)

if __name__ == '__main__':

    main()

Output:

...

Inside hello_there()

Acquiring lock

Lock Acquired

Inside bye()

Acquiring lock

Lock Acquired

...

Interested to learn python in detail? Come and Join the python course.

Related questions

0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 26, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Mar 22, 2021 in Java by dante07 (13.1k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...