How to lock a thread in Python?

0 votes
I am new to Python. I am learning the threading concept in Python. I want to know how to lock a thread when two threads are trying to access a shared resource
Jul 10, 2019 in Python by Neel
• 3,010 points
60 views

1 answer to this question.

0 votes

Please refer to the following code to solve the problem.

from threading import Lock, Thread
lock = Lock()
g = 0

def add_one():
   """
   Just used for demonstration. It's bad to use the 'global'
   statement in general.
   """
   
   global g
   lock.acquire()
   g += 1
   lock.release()

def add_two():
   global g
   lock.acquire()
   g += 2
   lock.release()

threads = []
for func in [add_one, add_two]:
   threads.append(Thread(target=func))
   threads[-1].start()

for thread in threads:
   """
   Waits for threads to complete before moving on with the main
   script.
   """
   thread.join()

print(g)

The output of this program will be 3

answered Jul 10, 2019 by Arvind
• 2,980 points

Related Questions In Python

0 votes
1 answer

How do you add a background thread to flask in Python?

The example below creates a background thread ...READ MORE

answered Nov 19, 2018 in Python by Nymeria
• 3,540 points
18,978 views
0 votes
1 answer

How to add a new line in Python?

You can use '\n' for a next ...READ MORE

answered May 2, 2018 in Python by aayushi
• 750 points
286 views
0 votes
2 answers

How to calculate square root of a number in python?

calculate square root in python >>> import math ...READ MORE

answered Apr 2, 2019 in Python by anonymous
516 views
+1 vote
1 answer

How to print first character of each word in upper case of a string in Python

You can use split() using space as ...READ MORE

answered Jun 1, 2018 in Python by george
• 200 points
4,307 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 953 views
0 votes
0 answers
+1 vote
1 answer

How to install a module in Python 3.6 ?

If you are using Ubuntu then the ...READ MORE

answered Jun 25, 2019 in Python by Arvind
• 2,980 points
177 views
+1 vote
1 answer

How to convert records from csv to a list in Python?

If you are using Python 3.x then ...READ MORE

answered Jun 25, 2019 in Python by Arvind
• 2,980 points

edited Jun 26, 2019 by Kalgi 517 views