Python多线程编程中的锁问题实例及解析

原创 た 入场券 2025-01-20 14:36 22阅读 0赞

在Python的多线程编程中,锁(Lock)是一种同步原语,用于保护共享资源不被多个线程同时访问。

以下是一个简单的锁问题实例:

  1. import threading
  2. # 共享资源
  3. counter = 0
  4. class CounterThread(threading.Thread):
  5. def __init__(self, name):
  6. super(CounterThread, self).__init__(name)
  7. self.count_lock = threading.Lock()
  8. def increment(self):
  9. with self.count_lock:
  10. counter += 1
  11. print(f"{self.name}: Counter incremented from {counter} to {counter+1}")
  12. # 创建两个线程,一个增加计数器,另一个验证计数器
  13. thread1 = CounterThread("Thread1")
  14. thread2 = threading.Thread(target=check_counter, args=(thread1.increment, thread2.name))))
  15. thread1.start()
  16. thread2.start()

在这个例子中,CounterThread类负责维护共享的计数器。线程1通过increment方法增加计数器,线程2验证计数器是否正确。

在多线程编程中,锁能够防止多个线程同时访问和修改共享资源,从而保证程序的正确性和并发性。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,22人围观)

还没有评论,来说两句吧...

相关阅读