You are on page 1of 1

11/28/12

A Pthreads Tutorial, written by Andrae Muys


All Unix's are multi-tasking operating systems. The process model used by unix permits a user to run multiple processes simultaneously making it one of the most powerful and flexible multi-programming models in use today. Under the traditional unix model, processes are all created in the same way, by using the fork() system call. Fork() produces a second copy of the calling process. This second copy is identical to the original, except that the return value of fork() in the child = 1, while the return value of fork() in the parent = the child's pid. So the normal use of fork() is:
[ d op a r e n ts t u f f ] p p i d=f o r k( ) ; i f( p p i d<0 ){ f o r k _ e r r o r _ f u n c t i o n( ) ; }e l s ei f( p p i d= =1 ){ c h i l d _ f u n c t i o n( ) ; }e l s e{ p a r e n t _ f u n c t i o n( ) ; }

Note that this only works because fork() returns two completely independent copies of the original process. Each process has its own address space, with its own copies of its variables, which are completely independent of the same variables in the other process (the only exception to this is with some SysV IPC variables, but these are special cases). This independence, while providing memory protection and therefore stability, causes problems when you want to have multiple processes working on the same task/problem. Yes you can use pipes or SysV IPC, but there are still serious problems. The cost of switching between multiple processes is relatively high. There are often severe limits on the number of processes the scheduler can handle efficiently. Synchronisation variables, shared between multiple processes, are typically slow. For these reasons, and others, threads or Light Weight Processes(LWP) can be very useful. Threads share a common address space, and are often scheduled internally in a process, thereby avoiding a lot of the inefficiencies of multiple processes. One very popular API for threading an application is pthreads, also known as POSIX threads, P1003.1c, or ISO/IEC 9945-1:1990c. This API is the subject of todays tutorial. <<< Contents >>> Andrae Muys

www.cs.nmsu.edu/~jcook/Tools/pthreads/pthreads.html

1/1

You might also like