A lock should be considered to use, such as threading.Lock
. See lock-objects for more info.
The accepted answer CAN print 10 by thread1, which is not what you want. You can run the following code to understand the bug more easily.
def thread1(threadname):
while True:
if a % 2 and not a % 2:
print "unreachable."
def thread2(threadname):
global a
while True:
a += 1
Using a lock can forbid changing of a
while reading more than one time:
def thread1(threadname):
while True:
lock_a.acquire()
if a % 2 and not a % 2:
print "unreachable."
lock_a.release()
def thread2(threadname):
global a
while True:
lock_a.acquire()
a += 1
lock_a.release()
If thread using the variable for long time, coping it to a local variable first is a good choice.