| 1 |
/*********************************************************************** |
| 2 |
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC * |
| 3 |
* Copyright (C) 2001 by New Riders Publishing * |
| 4 |
* See COPYRIGHT for license information. * |
| 5 |
***********************************************************************/ |
| 6 |
|
| 7 |
#include <malloc.h> |
| 8 |
#include <pthread.h> |
| 9 |
#include <stdio.h> |
| 10 |
|
| 11 |
/* The key used to assocate a log file pointer with each thread. */ |
| 12 |
static pthread_key_t thread_log_key; |
| 13 |
|
| 14 |
/* Write MESSAGE to the log file for the current thread. */ |
| 15 |
|
| 16 |
void write_to_thread_log (const char* message) |
| 17 |
{ |
| 18 |
FILE* thread_log = (FILE*) pthread_getspecific (thread_log_key); |
| 19 |
fprintf (thread_log, "%s\n", message); |
| 20 |
} |
| 21 |
|
| 22 |
/* Close the log file pointer THREAD_LOG. */ |
| 23 |
|
| 24 |
void close_thread_log (void* thread_log) |
| 25 |
{ |
| 26 |
fclose ((FILE*) thread_log); |
| 27 |
} |
| 28 |
|
| 29 |
void* thread_function (void* args) |
| 30 |
{ |
| 31 |
char thread_log_filename[20]; |
| 32 |
FILE* thread_log; |
| 33 |
|
| 34 |
/* Generate the filename for this thread's log file. */ |
| 35 |
sprintf (thread_log_filename, "thread%d.log", (int) pthread_self ()); |
| 36 |
/* Open the log file. */ |
| 37 |
thread_log = fopen (thread_log_filename, "w"); |
| 38 |
/* Store the file pointer in thread-specific data under thread_log_key. */ |
| 39 |
pthread_setspecific (thread_log_key, thread_log); |
| 40 |
|
| 41 |
write_to_thread_log ("Thread starting."); |
| 42 |
/* Do work here... */ |
| 43 |
|
| 44 |
return NULL; |
| 45 |
} |
| 46 |
|
| 47 |
int main () |
| 48 |
{ |
| 49 |
int i; |
| 50 |
pthread_t threads[5]; |
| 51 |
|
| 52 |
/* Create a key to associate thread log file pointers in |
| 53 |
thread-specific data. Use close_thread_log to clean up the file |
| 54 |
pointers. */ |
| 55 |
pthread_key_create (&thread_log_key, close_thread_log); |
| 56 |
/* Create threads to do the work. */ |
| 57 |
for (i = 0; i < 5; ++i) |
| 58 |
pthread_create (&(threads[i]), NULL, thread_function, NULL); |
| 59 |
/* Wait for all threads to finish. */ |
| 60 |
for (i = 0; i < 5; ++i) |
| 61 |
pthread_join (threads[i], NULL); |
| 62 |
return 0; |
| 63 |
} |