fork in multi-threaded program

The problem with forking when you do have some threads running is that the fork only copies the CPU state of the one thread that called it. It’s as if all of the other threads just died, instantly, wherever they may be.

The result of this is locks aren’t released, and shared data (such as the malloc heap) may be corrupted.

pthread does offer a pthread_atfork function – in theory, you could take every lock in the program before forking, release them after, and maybe make it out alive – but it’s risky, because you could always miss one. And, of course, the stacks of the other threads won’t be freed.

Leave a Comment