Subj : Re: pthreads and fork To : comp.programming.threads From : Marcin 'Qrczak' Kowalczyk Date : Sat Feb 19 2005 09:16 pm Alexander Terekhov writes: > The cleanest solution is to have synchronous forkall() stuff with > subsequent ordinary termination/cleanup of threads you don't need > any more. I tested some other systems (with the help of friends and SourceForge's compile farm). The behavior of pthread_join on an evaporated thread indeed varies between systems: sometimes the thread is reported like a finished thread, sometimes it returns ESRCH or EINVAL, and sometimes it hangs (probably waiting for it to finish even though it doesn't exist). I don't know whether resources leak (other than user resources). There were no crashes. Cases when it succeeds were a minority, and it's hard to know about leaks if it fails, so I gave up trying to recover in such situation and I prevent it instead. Since I currently use pthreads only for making getaddrinfo/getnameinfo asynchronous, this means that ForkProcess in my language must wait until any pending Get{Addr,Name}InFo calls complete, and new calls are put on hold. This is the classical readers/writers problem where pthreads are readers and fork is a writer. This also means that I should be careful with introducing pthreads for other uses when they might wait indefinitely. For example waitpid (on systems where it works to wait from a different thread; fortunately this should be testable at configure time). Well, in the case of waitpid the problem is solvable - the worker pthread can be canceled and recreated after fork. * * * Since I implement my own threads (pthreads are used only to make some functions asynchronous), I can decide myself about their behavior on fork. And since I'm designing the language to make asynchronous cancelation quite safe, I decided that fork should cancel other threads using the regular mechanism for asynchronous signals; in particular if a thread has signals blocked, it will continue for some time in the child process. Of course not every computation is safe to be forked; if a thread has signals blocked and is going to write to stdout, the write might happen twice (and C fork has the same problem with I/O buffers). But I believe that cancelation is a better default than evaporation, at least in a language which supports asynchronous signals, exceptions and garbage collection. My equivalent of pthread_atfork can be used to make more cases safe and avoid e.g. duplicating output. -- __("< Marcin Kowalczyk \__/ qrczak@knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ .