fork in multi-threaded program

后端 未结 2 1845
感动是毒
感动是毒 2020-12-01 05:27

I\'ve heard that mixing forking and threading in a program could be very problematic, often resulting with mysterious behavior, especially when dealing with shared resources

2条回答
  •  生来不讨喜
    2020-12-01 06:12

    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.

提交回复
热议问题