ch4-tsd (thread-specific data)

Chapter_4     critical-section cleanup







tsd.c     ALP, p. 72-73


#include <stdio.h> // for fprintf(), sprintf(), stderr,
// fopen(), fclose(), FILE, NULL
#include <pthread.h> // for pthread_t, pthread_create(), pthread_join(),
// pthread_key_t, pthread_key_create(), pthread_self(),
// pthread_getspecific(), pthread_setspecific()
// pthread.h includes bits/pthreadtypes.h, which defines:
// /usr/include/x86_64-linux-gnu/bits/pthreadtypes.h:
// typedef unsigned long int pthread_t;
// typedef unsigned int pthread_key_t;

// The key used to associate a log file pointer with each thread:
static pthread_key_t thread_log_key;

void write_to_thread_log (const char *message); // write to log file
void close_thread_log (void * thread_log); // Close log file pointer
void * thread_function (void * args); // create log file, write log

int main() // thread-specific data
{
int i;
pthread_t threads[5];
/* Create a key to associate thread log file pointers in
thread-specific data. Use close_thread_log() to clean up the file
pointers. */
pthread_key_create (&thread_log_key, close_thread_log);

for (i = 0; i < 5; i++) /* Create threads to do the work */
{pthread_create (&(threads[i]), NULL, thread_function, NULL);}
/* Wait for all threads to finish. */
for (i = 0; i < 5; i++)
{pthread_join (threads[i], NULL);}

return 0;
}

// Write `message' to the log file for the current thread:
void write_to_thread_log (const char *message)
{
FILE * thread_log = (FILE*) pthread_getspecific(thread_log_key);
fprintf (thread_log, "%s\n", message);
}

// Close the log file pointer `thread_log':
void close_thread_log (void * thread_log)
{
fclose((FILE*)thread_log);
}

void * thread_function (void * args)
{
char thread_log_filename[40];
FILE * thread_log;
/* Generate the filename for this thread's log file: */
sprintf (thread_log_filename, "thread-%lu.log",
(unsigned long) pthread_self());
/* Open the log file for writing: */
thread_log = fopen (thread_log_filename, "w");
fprintf(stderr, "Opening file \"%s\"\n", thread_log_filename);
// Store the file pointer in thread-specific data under thread_log_key:
pthread_setspecific (thread_log_key, (void *) thread_log);
write_to_thread_log ("Thread starting...");
/* Do work here... */
return NULL;
}
/*
gcc tsd.c -o tsd -lpthread
./tsd
Opening file "thread-140346443351808.log"
Opening file "thread-140346409780992.log"
Opening file "thread-140346434959104.log"
Opening file "thread-140346426566400.log"
Opening file "thread-140346418173696.log"

rm thread*.log // clean
*/









Chapter_4     critical-section BACK_TO_TOP cleanup



Comments

Popular posts from this blog

Contents