您的位置:首页 > 其它

线程特定数据

2013-01-10 21:35 253 查看

1 概念定义

  单线程C程序有2类基本数据:局部数据和全局数据。而对于多线程C程序而言,添加了第3类数据:线程特定数据。线程特定数据与全局数据非常相似,区别在于前者为线程专有,其基于每线程进行维护。TSD(特定于线程的数据)是定义和引用线程专用数据的唯一方法。每个线程特定数据项都与一个作用于进程内所有线程的键关联。通过使用key,线程可以访问基于每线程进行维护的指针(void
*)。

2 参考代码

#include <stdio.h>
#include <malloc.h>
#include <pthread.h>

#define FILE_NAME_MAX_LEN (256)
#define THREAD_MAX_NUM (5)

/* 一个作用于进程内所有线程的键 */
static pthread_key_t thread_log_key;

/* 当前线程写日志 */
void write_log(const char* message)
{
FILE *logfp = (FILE*) pthread_getspecific(thread_log_key);

fprintf(logfp, "%s\n", message);
}

/* 关闭文件指针 */
void close_log(void* logfp)
{
fclose((FILE*) logfp);
}

/* 线程入口函数 */
void* thread_function(void* args)
{
FILE *logfp = NULL;
char fname[FILE_NAME_MAX_LEN] = {0};

snprintf(fname, sizeof(fname), "thread-%d.log", (int)pthread_self());

logfp = fopen(fname, "w");
if(NULL == logfp)
{
return NULL;
}

/* 将文件指针与key相关联 */
pthread_setspecific(thread_log_key, logfp);

write_log("Thread starting.");

/* Do work here... */

return NULL;
}

int main(void)
{

int idx=0, ret=0;
pthread_t threads[THREAD_MAX_NUM];

/* 创建线程日志key,并设置close_log()进行清理操作 */
ret = pthread_key_create(&thread_log_key, close_log);

/* 创建线程 */
for(idx=0; idx<THREAD_MAX_NUM; idx++)
{
pthread_create(&(threads[idx]), NULL, thread_function, NULL);
}

/* 等待所有线程结束,并回收资源 */
for(idx=0; idx<THREAD_MAX_NUM; idx++)
{
pthread_join(threads[idx], NULL);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: