Python0017 thread lock
Some problems with thread creation and threads have been introduced in the previous article. This article reproduces the problem mentioned in the previous article and uses thread locks to solve that problem.
After the thread is locked, other threads will wait for the lock to be released before continuing to execute when they encounter the lock.
Here is the code:
import threading import time sumab = -1 def a_thread(): overall summation time.sleep(0.1) sumab = 0 print("a:","sumab=0") time.sleep(0.1) sum = 1+2 print("a:","sumab=1+2") time.sleep(0.1) print("a:","print sum") print("1+2=",sumab) def b_thread(): overall summation time.sleep(0.1) sumab = 1 print("b:","sumab=1") time.sleep(0.1) sum = 3+4 print("b:","sumab=3+4") time.sleep(0.1) print("b:","print sum") print("3+4=",sumab) a=threading.Thread(target=a_thread) b=threading.Thread(target=b_thread) a.start() b.start() # A certain execution result # a: sumb=0 # b: sumab=1 # a: sumb=1+2 # b: sumab=3+4 # a: print sum # 1+2= 7 # b: print sum # 3+4= 7 sumab_lock=threading.Lock() def c_thread(): global sumab,sumab_lock time.sleep(0.1) #lock sumab_lock.acquire() sumab = 0 time.sleep(0.1) sum = 1+2 time.sleep(0.1) print("1+2=",sumab) #release lock sumab_lock.release() def d_thread(): global sumab,sumab_lock time.sleep(0.1) #lock sumab_lock.acquire() sumab = 1 time.sleep(0.1) sum = 3+4 time.sleep(0.1) print("3+4=",sumab) #release lock sumab_lock.release() c=threading.Thread(target=c_thread) d=threading.Thread(target=d_thread) c.start() d.start() # 1+2= 3 # 3+4= 7 #or # 3+4= 7 # 1+2= 3