threading.loock()--python互斥锁
获取和释放的方式
1. acquire()获取锁、release()释放锁
from log import * import threading import time # 共享资源 counter = 0 lock = threading.Lock() def increment(): global counter lock.acquire() try: counter += 1 info("CUrrent thread: {}, Counter: {}".format(threading.current_thread().name, counter)) finally: # 释放锁 lock.release() # 创建10个线程 threads = [] for _ in range(10): t = threading.Thread(target=increment) threads.append(t) t.start() # 等待所有线程完成 for t in threads: t.join()2. with 自动获取和释放锁
from log import * import threading import time counter = 0 lock = threading.Lock() def increment(): global counter # 使用 with 语句自动管理锁的获取和释放 with lock: counter += 1 info("Currrent thread: {0}, counter: {1}".format(threading.current_thread().name, counter)) # 创建10个线程 threads = [] for _ in range(10): t = threading.Thread(target=increment) threads.append(t) t.start() for t in threads: t.join()