在Python中,同步(Synchronization)是指控制多个线程或进程对共享资源的访问,以避免数据不一致或竞争条件的问题。同步机制确保在任何时刻只有一个线程或进程可以访问特定的资源。
以下是一个使用互斥锁(Lock)的简单示例:
import threading
# 创建一个锁
lock = threading.Lock()
# 共享资源
counter = 0
def increment():
global counter
for _ in range(100000):
lock.acquire()
counter += 1
lock.release()
# 创建两个线程
thread1 = threading.Thread(target=increment)
thread2 = threading.Thread(target=increment)
# 启动线程
thread1.start()
thread2.start()
# 等待线程完成
thread1.join()
thread2.join()
print(f"Final counter value: {counter}")
原因:两个或多个线程互相等待对方释放资源。 解决方法:
import threading
lock1 = threading.Lock()
lock2 = threading.Lock()
def thread_1_task():
with lock1:
with lock2:
print("Thread 1")
def thread_2_task():
with lock1: # 确保获取锁的顺序一致
with lock2:
print("Thread 2")
t1 = threading.Thread(target=thread_1_task)
t2 = threading.Thread(target=thread_2_task)
t1.start()
t2.start()
t1.join()
t2.join()
通过以上方法,可以有效管理和解决Python中的同步问题,确保程序的正确性和可靠性。
领取专属 10元无门槛券
手把手带您无忧上云