What might happen if I use a boolean value to control a cycle of a thread if I don't lock it before checking its value. Can an exception be raised?
Notice that is not a problem if my cycle run once more, but if possible I'd like to avoid the cost of locking the resource
# self is the same object in the 2 functions
def __init__(self):
self.status=True
# thread 1
def stop(self):
# Lock acquired to avoid concurrent writes
self.lock.acquire()
self.status=False
self.lock.release()
# thread 2
def thread_func(self):
while self.status:
# Do stuff
# Not important if it does a cycle more after status is set to false
CodePudding user response:
There is no need to lock. Python use the GIL (global interpreter lock) to prevent accesing objects at the same time from different threads.
In CPython, the global interpreter lock, or GIL, is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once. The GIL prevents race conditions and ensures thread safety [https://wiki.python.org/moin/GlobalInterpreterLock]
Lock should be used when you want to prevent access to some objects during some operation involving more than one bytecode for example if you had several threads doing this:
x.data1 = 10
x.data2 = 20
x.process()
you could end up calling x.process()
with mixed data, if threads switch between first and second line, or maybe x.process()
could be called twice with the same data.
In that case you should use a lock.
In general the problem arise when you more than one related atomic operations which involves reads and writes.
Note that a single
x = 1
is not atomic and python could switch threads after reading x
but before reassign it. So if you havemore than one thread with that line you should use locks or you will have unpredictable behavior. (x
could have a smaller value than waht you expect)