libtalloc_threads man page

The talloc library is not internally thread-safe, in that accesses to variables on a talloc context are not controlled by mutexes or other thread-safe primitives.

However, so long as talloc_disable_null_tracking() is called from the main thread to disable global variable access within talloc, then each thread can safely use its own top level talloc context allocated off the NULL context.

The problem comes when one thread wishes to move some memory allocated on its local top level talloc context to another thread. Care must be taken to add data access exclusion to prevent memory corruption. One method would be to lock a mutex before any talloc call on each thread, but this would push the burden of total talloc thread-safety on the poor user of the library.

A much easier way to transfer talloced memory between threads is by the use of an intermediate, mutex locked, intermediate variable.

An example of this is below - taken from test code inside the talloc testsuite.

The main thread creates 1000 sub-threads, and then accepts the transfer of some thread-talloc'ed memory onto its top level context from each thread in turn.

A pthread mutex and condition variable are used to synchronize the transfer via the intermediate_ptr variable.