doc: The same JSON values must not be encoded in parallel
[jansson.git] / doc / portability.rst
1 ***********
2 Portability
3 ***********
4
5 Thread safety
6 -------------
7
8 Jansson is thread safe and has no mutable global state. The only
9 exception are the memory allocation functions, that should be set at
10 most once, and only on program startup. See
11 :ref:`apiref-custom-memory-allocation`.
12
13 There's no locking performed inside Jansson's code, so a multithreaded
14 program must perform its own locking if JSON values are shared by
15 multiple threads. Jansson's reference counting semantics may make this
16 a bit harder than it seems, as it's possible to have a reference to a
17 value that's also stored inside a list or object. Modifying the
18 container (adding or removing values) may trigger concurrent access to
19 such values, as containers manage the reference count of their
20 contained values. Bugs involving concurrent incrementing or
21 decrementing of deference counts may be hard to track.
22
23 The encoding functions (:func:`json_dumps()` and friends) track
24 reference loops by modifying the internal state of objects and arrays.
25 For this reason, encoding functions must not be run on the same JSON
26 values in two separate threads at the same time. As already noted
27 above, be especially careful if two arrays or objects share their
28 contained values with another array or object.
29
30 If you want to make sure that two JSON value hierarchies do not
31 contain shared values, use :func:`json_deep_copy()` to make copies.
32
33 Locale
34 ------
35
36 Jansson works fine under any locale.
37
38 However, if the host program is multithreaded and uses ``setlocale()``
39 to switch the locale in one thread while Jansson is currently encoding
40 or decoding JSON data in another thread, the result may be wrong or
41 the program may even crash.
42
43 Jansson uses locale specific functions for certain string conversions
44 in the encoder and decoder, and then converts the locale specific
45 values to/from the JSON representation. This fails if the locale
46 changes between the string conversion and the locale-to-JSON
47 conversion. This can only happen in multithreaded programs that use
48 ``setlocale()``, because ``setlocale()`` switches the locale for all
49 running threads, not only the thread that calls ``setlocale()``.
50
51 If your program uses ``setlocale()`` as described above, consider
52 using the thread-safe ``uselocale()`` instead.