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 in Python by Neel
• 3,010 points
26 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 by Arvind
• 2,960 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,520 points
9,178 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
121 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 in Python by anonymous
254 views
0 votes
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
2,411 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 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 337 views
+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 in Python by Arvind
• 2,960 points
89 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 in Python by Arvind
• 2,960 points

edited Jun 26 by Kalgi 53 views