Wednesday, March 12, 2008

[Programming] Threads (1)

Another important concept in multi-tasking operating system is threads. We have learned that a program can fork a child process to do a different thing. However, at times the overhead of creating a new child process is heavy, especially for some embedded systems which only have limited resources for use. The fact behind this is that a new copy of the original process will be created when forking, such as the memory space and file descriptors. That's what we mentioned before that child process is schedueled independently of the parent process.

In order to realize multi-tasking with light overhead, some new concepts are introduced to multi-tasking programming, such as light-weight process and threads. Sometimes people just call threads as light-weight processes for the sake of simplicity, although they are not the same thing (for details, you can refer to Light-weight process in wikipedia).

So in the view of the resource usage, the new created thread does not copy the original system resources used by the creating thread. It shares the same memory space (heap), global variables, file descriptors, signal handlers and other system resources as the original. However, threads have their own stack space.

If we take a look at the thread in the view of implementation, a thread exists within a process, or more precisely, a thread is a sequence of control within a process. Indeed, a process has at least one thread of execution (also called primary or main thread). This primary thread can create additional threads, and all these threads run the same program in the same process, but they may execute a different part of the program at any time.

No comments: