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
120 views

2 answers 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
0 votes
  1. Lock objects can release the lock at any position of code. For example if test1 function calls the lock so this lock can be opened by another function. But in RLock thread must release it once for each time it has acquired it.
     

  2. In recursive call of function Lock will produce the deadlock that can be overcome by Rlock.

answered Jul 23 by sahil
• 540 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
23,877 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
339 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
625 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
5,178 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 1,349 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
267 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 1,680 views