Computer Science 354
Operating Systems
Dickinson College
Spring Semester 2000
Grant Braught
/*
* tcreate.c
* Example program that demonstrates
* how to create threads in C using the
* pthread library.
*
* Compile with:
* cc tcreate.c -lpthread
* Grant Braught
* Dickinson College
* (c) 2000
*/
#define _REENTRANT
#include
#include
#include
#include
void randwait(void);
void *threadFunc1(void *num);
// Global variable X that will be modified by
// all of the threads to illustrate that they
// are running in the same address space.
int X = 1;
int main(int argc, char *argv[])
{
int threadCount;
int i;
long randSeed;
// Names for the threads...
char Name[] = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Holders for the thread ID's...
pthread_t threadIDs[52];
// Check to make sure there are the right number of
// command line arguments.
if (argc != 3) {
printf("Use: tcreate \n");
exit(-1);
}
// Get the command line arguments and convert them
// into integers.
threadCount = atoi(argv[1]);
randSeed = atol(argv[2]);
// Initialize the random number generator.
srand48(randSeed);
// Make sure the number of threads is less than the number of names
// available...
if (threadCount > 52) {
printf("Maximum number of threads is 52\n");
exit(-1);
}
printf("\ntcreate.cpp\n\n");
printf("Create %d threads each of which will announce its\n",
threadCount);
printf("existence, sleep for a random number of seconds [3...5]\n");
printf("and then announce that it is exiting.\n\n");
printf("main: X = %d\n\n", X);
for (i=1; i<=threadCount; i++) {
// create the threads.
pthread_create(&threadIDs[i], NULL,
threadFunc1, (void *)&Name[i]);
}
// Main must wait for the threads to finish before exiting.
// If main exists all of the threads are killed.
for (i=1; i<=threadCount; i++) {
pthread_join(threadIDs[i], NULL);
}
printf("main: X = %d\n\n", X);
}
void *threadFunc1(void *name) {
printf("Thread %c starting up...(X = %d)\n",
*(char *)name,X);
X++;
randwait();
printf("Thread %c exiting...(X = %d)\n",
*(char *)name,X);
}
void randwait( void )
{
int i,len;
// Generate a random number...
len = (int) ((drand48() * 5) + 3);
sleep(len);
}