counter
进行累加import threading
import time
counter = 0
temp_count = 0
def increment():
global counter, temp_count
for _ in range(1000):
counter += 1
temp = temp_count
time.sleep(0.0001)
temp_count = temp + 1
start = time.time()
threads = []
for _ in range(10):
t = threading.Thread(target=increment)
threads.append(t)
t.start()
for t in threads:
t.join()
end = time.time()
print("Final counter value:", counter)
print("Final temp_count value:", temp_count)
print(f"总共耗时:{end - start}")
# 运行结果
Final counter value: 10000
Final temp_count value: 1001
总共耗时:0.5465419292449951
counter
做多线程累积时,尽管 counter += 1
是非原子操作,但是由于 CPU 执行太快,因此我们很难复现线程不安全的情况,因此我们使用 temp_count
写法进行手动模拟。import threading
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if self.balance >= amount:
# 发生线程切换
self.balance -= amount
print(f"Withdrawal successful. Balance: {self.balance}")
else:
print("Insufficient funds")
def deposit(self, amount):
self.balance += amount
print(f"Deposit successful. Balance: {self.balance}")
if __name__ == "__main__":
account = BankAccount(1000)
# 创建多个线程进行取款存款操作
threads = []
for _ in range(5):
t = threading.Thread(target=account.withdraw, args=(account, 200))
threads.append(t)
t.start()
for t in threads:
t.join()
self.balance >= amount
后切换到线程2,线程2正常取款200,然后切换回线程1,导致此时余额为-2200。locked、release 显式获取锁和释放锁
的用法。import threading
class BankAccount:
def __init__(self, balance):
self.balance = balance
self.lock = threading.Lock()
def withdraw(self, amount):
self.lock.locked()
if self.balance >= amount:
self.balance -= amount
print(f"Withdrawal successful. Balance: {self.balance}")
else:
print("Insufficient funds")
self.lock.release()
def deposit(self, amount):
self.lock.locked()
self.balance += amount
print(f"Deposit successful. Balance: {self.balance}")
self.lock.release()
if __name__ == "__main__":
account = BankAccount(1000)
# 创建多个线程进行取款存款操作
threads = []
for _ in range(5):
t = threading.Thread(target=account.withdraw, args=(account, 200))
threads.append(t)
t.start()
for t in threads:
t.join()
import threading
class BankAccount:
def __init__(self, balance):
self.balance = balance
self.lock = threading.Lock()
def withdraw(self, amount):
with self.lock:
if self.balance >= amount:
self.balance -= amount
print(f"Withdrawal successful. Balance: {self.balance}")
else:
print("Insufficient funds")
def deposit(self, amount):
with self.lock:
self.balance += amount
print(f"Deposit successful. Balance: {self.balance}")
if __name__ == "__main__":
account = BankAccount(1000)
# 创建多个线程进行取款存款操作
threads = []
for _ in range(5):
t = threading.Thread(target=account.withdraw, args=(account, 200))
threads.append(t)
t.start()
for t in threads:
t.join()
RLock 和 Semaphore
import threading
class SharedCounter:
'''
A counter object that can be shared by multiple threads.
'''
_lock = threading.RLock()
def __init__(self, initial_value = 0):
self._value = initial_value
def incr(self,delta=1):
'''
Increment the counter with locking
'''
with SharedCounter._lock:
self._value += delta
def decr(self,delta=1):
'''
Decrement the counter with locking
'''
with SharedCounter._lock:
self.incr(-delta)
import urllib.request
from threading import Semaphore
# At most, five threads allowed to run at once
_fetch_url_sema = Semaphore(5)
def fetch_url(url):
with _fetch_url_sema:
return urllib.request.urlopen(url)
? 你好,我是 Lorin 洛林,一位 Java 后端技术开发者!座右铭:Technology has the power to make the world a better place.
? 我对技术的热情是我不断学习和分享的动力。我的博客是一个关于Java生态系统、后端开发和最新技术趋势的地方。
? 作为一个 Java 后端技术爱好者,我不仅热衷于探索语言的新特性和技术的深度,还热衷于分享我的见解和最佳实践。我相信知识的分享和社区合作可以帮助我们共同成长。
? 在我的博客上,你将找到关于Java核心概念、JVM 底层技术、常用框架如Spring和Mybatis 、MySQL等数据库管理、RabbitMQ、Rocketmq等消息中间件、性能优化等内容的深入文章。我也将分享一些编程技巧和解决问题的方法,以帮助你更好地掌握Java编程。
? 我鼓励互动和建立社区,因此请留下你的问题、建议或主题请求,让我知道你感兴趣的内容。此外,我将分享最新的互联网和技术资讯,以确保你与技术世界的最新发展保持联系。我期待与你一起在技术之路上前进,一起探讨技术世界的无限可能性。
? 保持关注我的博客,让我们共同追求技术卓越。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。