Threads and fork()

Combining POSIX threads and the fork() system call can be a bit messy. Here’s some facts you may not be aware of:

  1. A fork() call only clones the current thread
  2. This can have unintentional effects

The most noticable effect of this, for aspiring thread users, is that it’s unsafe to start any threads before doing the daemonization double fork().

A less obvious problem, though, is that any locks that are held by threads other than the current thread will remain in a locked state within the child’s context until the heat death of the universe. In situations where there are global background objects that keep locks, this means that doing much beyond an exec() is unsafe and, if that exec() fails, it is unsafe to call exit() if any global destructors touch locks. Use _exit() instead.


No Responses to “Threads and fork()”

Responses are currently closed, but you can trackback from your own site.

Comments are closed.