#!/usr/bin/python # -*-coding:utf-8-*- import threading # 假定这是你的银行存款: balance = 0 block = threading.Lock() def change_it(n): # 先存后取,结果应该为0: global balance block.acquire() balance = balance + n balance = balance - n block.release() def run_thread(n): for i in range(100000): change_it(n) if __name__ == "__main__": t1 = threading.Thread(target=run_thread, args=(5,)) t2 = threading.Thread(target=run_thread, args=(8,)) t1.start() t2.start() t1.join() t2.join() print(balance)
threading.Lock
最新推荐文章于 2025-01-21 11:46:08 发布
本文提供了一个使用Python实现的简单示例,演示了如何利用线程锁来保护多个线程间共享资源的一致性。通过两个线程分别对全局变量进行加减操作,展示线程同步的重要性。
3万+

被折叠的 条评论
为什么被折叠?



