Python多线程编程中的锁问题实例及解析
在Python的多线程编程中,锁(Lock)是一种同步原语,用于保护共享资源不被多个线程同时访问。
以下是一个简单的锁问题实例:
import threading
# 共享资源
counter = 0
class CounterThread(threading.Thread):
def __init__(self, name):
super(CounterThread, self).__init__(name)
self.count_lock = threading.Lock()
def increment(self):
with self.count_lock:
counter += 1
print(f"{self.name}: Counter incremented from {counter} to {counter+1}")
# 创建两个线程,一个增加计数器,另一个验证计数器
thread1 = CounterThread("Thread1")
thread2 = threading.Thread(target=check_counter, args=(thread1.increment, thread2.name))))
thread1.start()
thread2.start()
在这个例子中,CounterThread
类负责维护共享的计数器。线程1通过increment
方法增加计数器,线程2验证计数器是否正确。
在多线程编程中,锁能够防止多个线程同时访问和修改共享资源,从而保证程序的正确性和并发性。
还没有评论,来说两句吧...