|20-CS-694||Advanced Programming Techniques||Spring 2012|
A process created using the UNIX fork() function is expensive in setup time and memory space. In fact it is sometimes called a heavyweight process. Properties of a heavyweight process are:
Often it is sufficient to run a partial copy of a process with the other parts shared with other processes. Such copies can be realized by a thread (an example of a lightweight process) which has the following properties:
A thread is a stream of instructions that can be scheduled as an independent unit. It is important to understand the difference between a thread and a process. A process contains two kinds of information: resources that are available to the entire process such as program instructions, global data and working directory, and schedulable entities, which include program counters and stacks. A thread is an entity within a process that consists of the schedulable part of the process.
A fork() duplicates all the threads of a process. The problem with this is that fork() in a process where threads work with external resources may corrupt those resources (e.g., writing duplicate records to a file) because neither thread may know that the fork() has occurred.
When a new perl thread is created, all the data associated with the current thread is copied to the new thread, and is subsequently private to that new thread! This is similar in feel to what happens when a UNIX process forks, except that in this case, the data is just copied to a different part of memory within the same process rather than a real fork taking place.
A fork() induces a parent-child relationship between two processes. Thread creation induces a peer relationship between all the threads of a process.