在Python中,同步多线程可以通过使用`threading`模块提供的锁(Lock)和条件变量(Condition)等机制来实现。下面是一些基本的同步方法:
使用锁(Lock)
锁是最基本的同步机制,确保一次只有一个线程可以访问共享资源。
import threading创建一个锁对象lock = threading.Lock()def worker():获取锁lock.acquire()try:访问共享资源print(f"线程 {threading.current_thread().name} 获取到锁,访问共享资源")finally:释放锁lock.release()创建多个线程threads = [threading.Thread(target=worker) for _ in range(5)]启动线程for thread in threads:thread.start()等待所有线程结束for thread in threads:thread.join()
使用条件变量(Condition)
条件变量允许线程等待某个条件成立,或者通知其他线程某个条件已经成立。
import threading创建一个条件变量对象condition = threading.Condition()def worker(condition):with condition:等待条件成立condition.wait_for(lambda: True)访问共享资源print(f"线程 {threading.current_thread().name} 获取到条件,访问共享资源")创建多个线程threads = [threading.Thread(target=worker, args=(condition,)) for _ in range(5)]启动线程for thread in threads:thread.start()通知所有线程条件成立with condition:condition.notify_all()等待所有线程结束for thread in threads:thread.join()

使用事件(Event)
事件允许线程等待某些事件的发生,或者通知其他线程某些事件已经发生。
import threading创建一个事件对象event = threading.Event()def worker(event):等待事件发生event.wait()访问共享资源print(f"线程 {threading.current_thread().name} 获取到事件,访问共享资源")创建多个线程threads = [threading.Thread(target=worker, args=(event,)) for _ in range(5)]启动线程for thread in threads:thread.start()通知所有线程事件发生event.set()等待所有线程结束for thread in threads:thread.join()
使用RLock(可重入锁)
RLock允许同一个线程多次获取锁,而不会导致死锁。
import threading创建一个RLock对象rlock = threading.RLock()def worker():获取锁rlock.acquire()try:访问共享资源print(f"线程 {threading.current_thread().name} 获取到锁,访问共享资源")finally:释放锁rlock.release()创建多个线程threads = [threading.Thread(target=worker) for _ in range(5)]启动线程for thread in threads:thread.start()等待所有线程结束for thread in threads:thread.join()
以上示例展示了如何使用`Lock`、`Condition`、`Event`和`RLock`进行多线程同步。选择合适的同步机制取决于具体的应用场景和需求
