threaded, forked, rethreaded processes will deadlock

David Schultz das at FreeBSD.ORG
Wed Jan 21 23:15:24 PST 2009


On Thu, Jan 22, 2009, Daniel Eischen wrote:
> On Wed, 21 Jan 2009, David Schultz wrote:
> 
> >I think there *is* a real bug here, but there's two distinct ways
> >to fix it. When a threaded process forks, malloc acquires all its
> >locks so that its state is consistent after a fork. However, the
> >post-fork hook that's supposed to release these locks fails to do
> >so in the child because the child process isn't threaded, and
> >malloc_mutex_unlock() is optimized to be a no-op in
> >single-threaded processes. If the child *stays* single-threaded,
> >malloc() works by accident even with all the locks held because
> >malloc_mutex_lock() is also a no-op in single-threaded processes.
> >But if the child goes multi-threaded, then things break.
> >
> >Solution 1 is to actually unlock the locks in the child process,
> >which is what Brian is proposing.
> >
> >Solution 2 is to take the position that all of this pre- and
> >post-fork bloat in the fork() path is gratuitous and should be
> >removed. The rationale here is that if you fork with multiple
> >running threads, there's scads of ways in which the child's heap
> >could be inconsistent; fork hooks would be needed not just in
> >malloc(), but in stdio, third party libraries, etc. Why should
> >malloc() be special? It's the programmer's job to quiesce all the
> >threads before calling fork(), and if the programmer doesn't do
> >this, then POSIX only guarantees that async-signal-safe functions
> >will work.
> >
> >Note that Solution 2 also fixes Brian's problem if he quiesces all
> >of his worker threads before forking (as he should!) With the
> >pre-fork hook removed, all the locks will start out free in the
> >child.  So that's what I vote for...
> 
> The problem is that our own libraries (libthr included)
> need to malloc() for themselves, even after a fork() in
> the child.  After a fork(), the malloc locks should be
> reinitialized in the child if it was threaded, so that
> our implementation actually works for all the async
> signal calls, fork(), exec(), etc.  I forget the exact
> failure modes for very common cases, but if you remove
> the re-initialization of the malloc locks, I'm sure
> you will have problems.

If you can't implement functions that are required to be
async-signal-safe like fork() and exec() without malloc(), then
for now I guess we should go for something along the lines of what
Brian is proposing. If the app programmer has taken special pains
to ensure that all other threads are stopped when a fork happens,
the fork() call shouldn't return in the child with all the malloc
locks bogusly held.


More information about the freebsd-hackers mailing list