多线程之 pthread_key_*

#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!

 

转载于:https://my.oschina.net/tsh/blog/1486314

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值