Skip to content

Commit e9f812c

Browse files
committed
Update README with thread safety section
1 parent c1ecd23 commit e9f812c

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,41 @@ However, a tuple is lighter than a list.
204204
You can use `use_list=False` while unpacking when performance is important.
205205

206206

207+
### Thread safety (CPython 3.14+ free-threaded build)
208+
209+
msgpack is designed to be thread-safe when used with CPython 3.14's
210+
free-threaded build (PEP 703).
211+
212+
#### Thread-Safety Guarantees
213+
214+
* **Individual `Packer` and `Unpacker` instances are thread-safe**:
215+
You can safely call methods on the same `Packer` or `Unpacker` instance
216+
from multiple threads concurrently. All public methods are protected by
217+
critical sections that ensure atomic access to internal state.
218+
219+
* **Module-level functions are thread-safe**: Functions like `packb()` and
220+
`unpackb()` create their own instances internally and are safe to call
221+
from multiple threads.
222+
223+
#### Performance Considerations
224+
225+
While sharing a single `Packer` or `Unpacker` instance across threads is safe,
226+
it may serialize operations due to critical section locking. For optimal
227+
performance in multi-threaded applications, create separate instances per thread:
228+
229+
```python
230+
import msgpack
231+
from concurrent.futures import ThreadPoolExecutor
232+
233+
def worker(data):
234+
# Each thread creates its own packer
235+
packer = msgpack.Packer()
236+
return packer.pack(data)
237+
238+
with ThreadPoolExecutor(max_workers=4) as executor:
239+
results = executor.map(worker, <data>)
240+
```
241+
207242
## Major breaking changes in the history
208243

209244
### msgpack 0.5

0 commit comments

Comments
 (0)