Bootstrap

Pyhton多线程——同步

一、使用锁实现同步

1. Lock锁

import threading
import time
from threading import Lock,RLock #可重入的锁

#1.用锁会影响性能,获取锁和释放锁都需要一定时间
#2.用锁可能会引起死锁
total = 0
lock = Lock()

def add():
    global total
    global lock
    for i in range(1000000):
        lock.acquire()
        total += 1
        lock.release()
    
def desc():
    global total
    global lock
    for i in range(1000000):
        lock.acquire()
        total -= 1
        lock.release()

if __name__ == "__main__":
    start_time = time.time()
    thread1 = threading.Thread(target=add)
    thread2 = threading.Thread(target=desc)
    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()
    print(total)
    end_time = time.time()
    print("cost time:", end_time-start_time)

运行结果:

;