void thread_function(void *args) { char log_filename[20]; FILE *thread_log; sprintf(log_filename,"thread%d.log",(int) pthread_self()); thread_log = fopen(log_filename,"w"); pthread_setspecific(log_key,thread_log); write_to_thread_log("Thread starting."); }
void* thread_function (void* args) { char thread_log_filename[20]; FILE* thread_log; /* Generate the filename for this thread’s log file. */ sprintf (thread_log_filename, "thread%d.log", (int) pthread_self ()); /* Open the log file. */ thread_log = fopen (thread_log_filename, "w"); /* Store the file pointer in thread-specific data under thread_log_key. */ pthread_setspecific (thread_log_key, thread_log); char* thread_msg = strdup(thread_log_filename); pthread_setspecific (thread_msg_key, thread_msg); write_to_thread_log ("Thread starting.", pthread_self()); /* Do work here... */ return NULL; }
void *thread_function (void *args) { char thread_log_filename[128]; char thread_start_message[128]; FILE *thread_log; sprintf (thread_log_filename, "thread%u.log", pthread_self()); thread_log = fopen (thread_log_filename, "w"); pthread_setspecific (thread_log_key, thread_log); //每个线程都设置自己的私有数据 sprintf (thread_start_message, "thread %u starting", pthread_self()); write_to_thread_log (thread_start_message); pthread_exit(NULL); }