Technical Linux questions
John Chambers
jc at trillian.mit.edu
Sat Feb 22 10:15:20 EST 2003
Jerry Feldman writes:
| WRT: Threads. Unlike a fork(), a thread is created by a thread create
| function (eg. pthread_create() for POSIX threads). It operates within
| the process space of the caller, so that no memory needs to be allocated
| (except possibly for the thread's stack and a control block). Also,
| context switching in threads is generally less expensive. We also need
| to consider that the thread model is portable to other operating
| systems, such as VMS, Windowz, et. al. where fork()/vfork() is primarily
| a Unix paradigm.
True, but this doesn't answer the question. The above
exactly describes the original vfork(), which created a new
process with its own stack but with the same data segment
as the parent. It's true that the intent was to make the
fork+exec sequence faster by saving a copy of memory that
was to be discarded. But in fact it could be used to create
multiple control points within the same program. I did this
on a couple of projects. Some sync operations were needed,
of course, but that's a different question from the
creation of "threads" and context switching, and can be
done in user space without any other system calls.
It's also true that vfork() is sometimes implemented as an
alias of fork(). This is rather a pity, as it interferes
with portability. I'd be tempted to provide an #ifdef that
overrides vfork with a routine that creates a kernel thread
on systems where vfork isn't implemented properly.
So far, it seems that we merely have two names for the same
concept. If by "vfork" you mean the original routine that
produced a new stack but shared the rest of the parent's
memory, there's the question of what a kernel thread does
that's materially different. (And note that listing other
tools in a "threads" package isn't an answer. You can add a
library of routines to anything.)
If I were to call pthread_create() followed by execve(), is
the result any different than fork+exec or vfork+exec? On a
system with a true vfork(), is there any of the pthread
library's functions that couldn't be implemented? It's
difficult to find answers such questions in the man pages.
The words are very different, but they seem to describe
something quite similar, if not identical.
One question that came up on a project: If a process calls
vfork() and one of the processes then does malloc(), is the
new memory accessible to both processes? The answer seems
to have been "Try it and find out." But this only tells you
the answer on the machine you test it on; it doesn't tell
you whether your code will work on another system, or after
an upgrade on the same machine. (Actually, a bit of digging
seems to turn up no clear answer to this question for
threads, either. Saying that malloc() is "thread safe" is
not an answer at all, since it doesn't tell you what the
behavior is or whether it's portable. ;-)
More information about the Discuss
mailing list