Skip to content
Advertisement

What happens to pthread_key_create() generated keys after a process fork?

From pthread_key_create FreeBSD man page: /comment

… The pthread_key_create() function creates a thread-specific data key visible to all threads in the process. Key values provided by pthread_key_create() are opaque objects used to locate thread-specific data. Although the same key value may be used by different threads, the values bound to the key by pthread_setspecific() are maintained on a per-thread basis and persist for the life of the calling thread.

I am assuming that produced pthread_key_t instances are bound to a process (hence the opaque word in the man page), and that these become invalid after a fork(). I couldn’t find any reference in existing man pages or documentation however.

Can anyone confirm/comment?

Advertisement

Answer

I am assuming that produced pthread_key_t instances are bound to a process

There is every reason to think that instances are process-specific, in that if you, say, record the representation of a key in shared memory then it is not meaningful to unrelated processes that happen to map the same shared memory segment.

(hence the opaque word in the man page),

But “opaque” has nothing in particular to do with that. It just means that there are no user-serviceable parts inside. You’re meant to use it only as a whole.

and that these become invalid after a fork().

That seems a bit of a jump. I would not expect that at all. fork() creates a nearly exact duplicate of the calling process, subject to a few explicitly enumerated exceptions, which are listed in the manual. Probably the biggest relevant one is that the new process contains only one thread (the one that called fork()). Invalidation of thread-specific data keys is not on the list, nor is the loss of thread-specific data of the one initial thread of the child.

I couldn’t find any reference in existing man pages or documentation however.

Exactly so.

HOWEVER, multi-threaded programs generally should not fork, as there is a high risk that the child process is left in an invalid state, such as with mutexes that are locked by threads that do not exist in the child. There are a few special cases, such as forking a child that immediately execs, but for the most part, you should not attempt to mix multithreading with multiprocessing.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement