前端开发入门到精通的在线学习网站

网站首页 > 资源文章 正文

python 线程安全(python线程安全的字典)

qiguaw 2024-10-17 12:29:25 资源文章 27 ℃ 0 评论

线程不安全(thread unsafety)

当多个线程同时修改共享变量,如果其中一个线程与另一个线程同时修改一个共享变量,那么将发生错误
程序举例
```
count = 0
def increment():
    global count
    count += 1
```

上一个程序为例子,如果两个线程同时执行,则会因为可能同时修改count而出错

如何将线程不安全改为线程安全(thread safety)

 加入线程锁,可以解决这个问题,当A线程访问count后,count会被锁定,访问结束后再分给其他线程,避免了其他线程同时修改count变量的情况
 ```
 class Counter:

def __init__(self):
    self.count = 0
    self.lock = Lock()

def increment(self):
    for _ in range(100000):
        self.lock.acquire()
        self.count += 1
        self.lock.release()
```

参考:https://www.educative.io/courses/python-concurrency-for-senior-engineering-interviews/xlm6QznGGNE

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表