PThread
This page contains some sample code written by Donghui Zhang using PThreads.
- Each sample program can be compiled and run independent to the other code. To make an executable out of a source code, write your own Makefile, or:
g++ -o first first.cc -lposix4 -lpthread
- first.cc: A simple program that creates two identical threads. Each thread reads a shared variable balance and add $1000 to it.
- second.cc: Allows a thread to take a parameter (in our example, the thread number), and allows a thread to sleep for a random number of seconds between reading the old balance and increasing it. You can see that data consistency may be violated.
- third.cc: Uses mutex lock to ensure that only one thread can enter its critical section.
- fourth.cc: Replace the mutex lock using a more general semaphore.
- pc_busy.cc: Producer-Consumer program with busy waiting. Here a producer (consumer) routine takes as parameter an array of two integers: thread number and the number of items it should produce.
You can use Google to find more information. Here are two sites I found useful in describing PThreads.