#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_PTHREAD (5)
pthread_key_t log_key;
void write_log(const char *msg)
{
if (!msg) {
return;
}
FILE *logFile = (FILE *)pthread_getspecific(log_key);
if (logFile) {
fprintf(logFile, "Thread :%ld, msg = %s\n", pthread_self(), msg);
}
}
void close_file(void *logFile)
{
if (logFile) {
fclose((FILE *)logFile);
logFile = NULL;
}
}
void *threadStart(void *args)
{
char filename[1024] = {'\0'};
FILE *logFile = NULL;
snprintf(filename, sizeof(filename) - 1, "thread_%ld.log", (long)pthread_self());
logFile = fopen(filename, "w");
if (!logFile) {
pthread_exit(NULL);
}
pthread_setspecific(log_key, (void *)logFile);
write_log("test pthread key!");
}
int main(int argc, char *argv[])
{
int i;
pthread_key_create(&log_key, close_file);
pthread_t thread[MAX_PTHREAD];
for (i = 0; i < MAX_PTHREAD; i++) {
pthread_create(&thread[i], NULL, threadStart, NULL);
}
for (i = 0; i < MAX_PTHREAD; i++) {
pthread_join(thread[i], NULL);
}
return 0;
}
编译输出:
cc key2.c -o key2 -lpthread
#运行生成 5 个文件
thread_1095313728.log thread_1117501760.log thread_1083889984.log thread_1109109056.log thread_1125894464.log
后面的数字为线程ID
cat thread_1083889984.log
Thread :1083889984, msg = test pthread key!
cat thread_1095313728.log
Thread :1095313728, msg = test pthread key!