I have a vague query. I have a shared library which is used by my server program. Whenever a new request arrives, I create a new thread to do task. Some said that if I fork a process the performance of shared library increases. I could not understand the intention.
Does shared library gives good performance in forked process than in threaded environment? I felt pretty strange about this fact
If your process uses threads, you must compile with -DREENTRANT and/or -D_THREADSAFE. This causes shared libraries
to use synchronization variable to protect internal data structures (such as the heap, for example). The extra locking and
unlocking obviously adds overhead.
If you just fork a new process, you needed compile with said options, meaning no locks are necessary.
Thanks for the reply Mr.jsmith. I never knew this. However when too many request arrive at a time (in my case around 20), is it OK to still fork process for new request?
Yes, depending upon what you are doing. Remember that fork() creates and process, not a thread, the primary difference between the two being that threads share the same data segment, whereas the child creates a copy, and thus the parent does not see changes the child makes nor does the child see changes the parent makes.
As an alternative to forking upon work request, some daemons will pre-create threads to avoid the overhead of thread creation continuously.
On the other hand processes are more expensive to switch. So you don't want to have too many active processes running at the same time. Threads are much cheaper.
It really depends on your threads library. For example, if you are using LinuxThreads, pThreads, or NPTL, chances are these libraries use kernel-assisted switching.
the perceived wisdom is that threads are faster and more efficient than
forks.
A lot of daemons spawn multiple listener processes too.
Though both are fast enough generally in a unix machine.
The most likely bottleneck will be in disk i/o.
If you have 50 threads writing to the same disk controller it's fairly likely most
of them will need to wait around anyway.