Building Threaded Applications


Building pthread-based applications is very simple. All that s necessary is to specify the pthreads library during compilation as:

 gcc -pthread threadapp.c -o threadapp -lpthread 

This will link our application with the pthread library, making the pthread functions available for use. Note also that we specify the -pthread option, which adds support for multithreading to the application (such as reentrancy). The option also ensures that certain global system variables (such as errno ) are provided on a per-thread basis.

One topic that s important to discuss in multithreaded applications is that of reentrancy. Consider two threads, each of which uses the strtok function. The strtok function uses an internal buffer for token processing of a string. This internal buffer can be used by only one user at a time, which is fine in the process world (forked processes), but in the thread world runs into problems. If each thread attempts to call strtok , then the internal buffer is corrupted, leading to undesirable (and unpredictable) behavior. To fix this, rather than use an internal buffer, a thread-supplied buffer could be used instead. This is exactly what happens with the thread-safe version of strtok , called strtok_r . The suffix _r indicates that the function is thread safe.




GNU/Linux Application Programming
GNU/Linux Application Programming (Programming Series)
ISBN: 1584505680
EAN: 2147483647
Year: 2006
Pages: 203
Authors: M. Tim Jones

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net