You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Enhance ConcurrentDictionary with get_locked and key_lock methods for improved thread safety; update README and tests accordingly. Bump version to 2.0.0.
A thread-safe dictionary. For atomic compound updates, use `update_atomic`.
75
+
A thread-safe dictionary. It has a few notable methods:
76
+
77
+
- assign_atomic()
78
+
- get_locked()
79
+
- update_atomic()
80
+
81
+
#### ConcurrentDictionary's `assign_atomic()`
82
+
83
+
Assigns a dictionary value under a key in a thread-safe way.
84
+
While `dict["somekey"] = value` is allowed, it's best to use `assign_atomic()` for clarity of intent. Using normal assignment will work but raise a UserWarning.
85
+
86
+
87
+
#### ConcurrentDictionary's `get_locked()`
88
+
89
+
When working with `ConcurrentDictionary`, you should use the `get_locked` method to safely read or update the value for a specific key in a multi-threaded environment. This ensures that only one thread can access or modify the value for a given key at a time, preventing race conditions.
76
90
77
91
```python
78
92
from concurrent_collections import ConcurrentDictionary
79
93
80
-
d = ConcurrentDictionary({'x': 1})
81
-
d['y'] =2# Simple assignment is thread-safe
82
-
# For atomic updates:
83
-
d.update_atomic('x', lambdav: v +1)
84
-
print(d['x']) # 2
94
+
d = ConcurrentDictionary({'x': "some value" })
95
+
96
+
# Safely read and update the value for 'x'
97
+
with d.get_locked('x') as value:
98
+
# value is locked for this thread
99
+
d['x'] ="new value"
100
+
```
101
+
102
+
#### ConcurrentDictionary's `update_atomic()`
103
+
104
+
Performs a thread-safe, in-place update to an existing value under a key.
105
+
106
+
```python
107
+
108
+
d = ConcurrentDictionary({'x': 1 })
109
+
d.update_atomic("x", lambdav: v +1) # d now contains 2 under the 'x' key.
0 commit comments