Getting Started - Threads with Shared Memory
By Min Xu, CS/ECE 757 TA, 2002
What are Threads
The multithreaded programming model is perhaps the most
popular model for shared memory programming. Threads
are light-weighted execution units inside each OS
process.
Thread vs. pthread
Look at the example code eg.c and eg_pthread.c
in the /p/course/cs757-markhill/public/ directory.
What's the difference? In short, eg.c uses Solaris thread
and eg_pthread.c uses POSIX thread. Generally, we recommend
POSIX thread because it is the stardard API across difference
platforms. Please type man threads for more information
on the difference between Solaris thread and POSIX thread.
Coding
Copy eg.c or eg_pthread.c (recommended)
into your own
directory.
To learn the concept of mutex, condition, etc., type:
man mutex
To bring a list of available function, type:
man threads or man pthreads
To consult a specific function, e.g. pthread_mutex_lock, type:
man pthread_mutex_lock
Compile: cc vs. gcc
To compile and link, type
cc -lpthread cg_pthread.c
To get better optimization, cc is recommended. However, for those
who are really interested in maximum optimization, please be careful
not to use thread-unsafe optimization options like -lfast.
Run your program
Running multithreaded executables are no different from normal execuables.
However, processor binding is something that you can control.
In the source code level, you can bind your threads to certain
processors, otherwise, the scheduling decision is left to the
OS.
Debug: dbx vs. gdb
Want to debug your program? The answer is sure, but try not to depend
on it. Both dbx
and gdb support multithreaded debugging, but race conditions
are generally hard to be replayed in the debugger. So write
your code more carefully.
Another useful tool to check you code is lock_lint.
Please see the book referred at the bottom of the page or the
man page on how to use it. But be aware that lock_lint is very
restrict on how to synchronize, some rules you may
not want to follow for performance reasons.
Now you may want to read through the
Multithreaded Programming Guide from
Sun Microsystems, and enjoy the power of multithreaded programming.