Pthreads Example
//
// Simple thread demo in plain C. The main declares a certain amount of
// "resources" (just an integer number) then starts two threads which
// "work through" the resources (mostly by printing that they did). This
// uses the standard, and truely awful, pthreads interface.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
/* Shared data. */
int depot;
/* Synchronizer. */
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
/* Thread info structure. */
struct threadinfo {
char *topr; /* What to print. */
int low, high; /* Random range. */
};
/* Thread function */
void * thbod(void *data)
{
struct threadinfo *tip = (struct threadinfo *)data;
while(1)
{
/* Choose a random number in range. */
int amt = rand() % (tip->high - tip->low + 1) + tip->low;
/* Acquire the lock and obtain needed resource. */
pthread_mutex_lock(&mutex);
if(depot < amt) amt = depot;
depot -= amt;
pthread_mutex_unlock(&mutex);
/* When the resource is exhausted, we're done. */
if(amt == 0) return;
/* Do that much "work." */
while(amt--) { printf("[%s]", tip->topr); fflush(stdout); }
printf("\n"); fflush(stdout);
}
}
/* Main starts two threads and waits for them to end. */
main()
{
/* These are the descriptive data for each thread. */
struct threadinfo ti1 = { "Z", 14, 18 };
struct threadinfo ti2 = { "EE", 8, 12 };
/* Two threads. These are actually something like thread ids. */
pthread_t th1, th2;
/* Seed the random number generator to vary behavior. */
srand(time(0) ^ 387*getpid());
/* Create the threads. Both start running thbod, and finish when
the function returns. The depot provides resources for the
the threads to run. */
depot = 3000;
pthread_create(&th1, NULL, thbod, &ti1);
pthread_create(&th2, NULL, thbod, &ti2);
/* Wait for each of them to be done. */
pthread_join(th1, NULL);
printf("First Done\n");
fflush(stdout);
pthread_join(th2, NULL);
printf("Second Done\n");
fflush(stdout);
}