Python0017 线程锁

Python0017 线程锁

在上篇文章中已经介绍过线程创建和线程的一些问题,本篇文章复现上篇文章提到的问题,并使用线程锁解决那个问题。

线程中加锁后,其他线程遇到这个锁后,会等待这个锁被释放才能继续执行。

下面是代码:

import threading
import time

sumab=-1


def a_thread():
    global sumab
    time.sleep(0.1)
    sumab=0
    print("a:","sumab=0")
    time.sleep(0.1)
    sumab=1+2
    print("a:","sumab=1+2")
    time.sleep(0.1)
    print("a:","print sum")
    print("1+2=",sumab)

def b_thread():
    global sumab
    time.sleep(0.1)
    sumab=1
    print("b:","sumab=1")
    time.sleep(0.1)
    sumab=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: sumab=0
# b: sumab=1
# a: sumab=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)
    #上锁
    sumab_lock.acquire()
    sumab=0
    time.sleep(0.1)
    sumab=1+2
    time.sleep(0.1)
    print("1+2=",sumab)
    #释放锁
    sumab_lock.release()

def d_thread():
    global sumab,sumab_lock
    time.sleep(0.1)
    
    #上锁
    sumab_lock.acquire()
    sumab=1
    time.sleep(0.1)
    sumab=3+4
    time.sleep(0.1)
    print("3+4=",sumab)
    #释放锁
    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
#或
# 3+4= 7
# 1+2= 3






猜你喜欢

转载自blog.csdn.net/moluth/article/details/79380863