Jansson is thread-safe and maintains no mutable global state, with the exception of memory allocation functions (which should be configured at most once during program startup).
However, Jansson does not perform internal locking. If you share JSON values across multiple threads, you must implement your own locking mechanism.
Key Thread Safety Risks:
- Reference Counting: Modifying a container (adding/removing values) can trigger concurrent access to values because containers manage the reference counts of their contents. This can lead to race conditions in reference count increments/decrements.
- Encoding Functions: Functions like
json_dumps() track reference loops by modifying the internal state of objects and arrays. You must not run encoding functions on the same JSON values in two separate threads simultaneously. - Shared Values: If multiple arrays or objects share the same contained values, modifying one can affect the others via reference counting.
Best Practice: To ensure two JSON hierarchies do not share any values, use json_deep_copy() to create independent copies.
// To prevent shared value issues across threads, create a deep copy
json_t *safe_copy = json_deep_copy(original_value);