- Threads are a mechanism to allow a program to do more than one thing at a time.
- A thread exists within a process. Threads are a finer-grained unit of execution than processes.
- Thread can create additional threads; all these threads run the same program in the same process, but each thread may be executing a different part of the program at any given time.
- The child process can modify its memory, close file descriptors etc., without affecting its parent, and vice versa.
- Threads offer lower consumption of system resources and easier communication between processes. The creating and the created thread share the same memory space, file descriptors, and other system resources as the original.
- There are many potential pitfalls to using threads or any other environment where the same memory space is shared by multiple processes.
- You must be careful about more than one process using the same variables at the same time.
- Many functions are not reentrant; that is, there cannot be more than one copy of that function running at the same
time (unless they are using separate data segments).
- Static variables declared inside functions are often a problem.
- Returning a pointer to statically allocated storage inside the
function is no good; another thread may execute that function and overwrite the return value before the first one is through using it.
- Setting or using global variables may create problems in threads.
- Semaphores, mutexes, disabling interrupts, or similar means should be used to protect variables, particularly aggregate variables,
against simultaneous access.
- POSIX threads (pthreads) provide a relatively portable implementation of lightweight processes.
- All thread functions and data types are declared in the header file
- They are in libpthread, so you should add -lpthread to the command line when you link your program.
Subsections
2006-03-24