Is it safe to thread after forking? Is it safe to thread after forking? unix unix

Is it safe to thread after forking?


creating many short-lived processes to distribute chunks of work to gets the more expensive with the more CPU cores I want to feed

Not really.

However, you can use message queues instead of forking individual processes for each piece of work.

Create a pile of processes that all read from a common queue. Put their work into the queue. No more forking. Many small tasks fed from a common queue.

And. No thread safety questions.


Your approach is fine under POSIX, as long as you don't create any MAP_SHARED shared memory regions that are shared among the forked processes. Once the processes are forked, they are independent.

See the POSIX documentation on fork().