Linux C 为线程添加各自的日志文件

/*
 *==============================================================================
 * Filename    :  tsd.c
 * Description :  
 * Author      :  RollStone (rs), jealdean@outlook.com
 * Created     :  10/14/2014 15:14
 * Copyright   :  2007-2014 RollStone. All Rights Reserved. 
 * Last_Change :  2014-10-14 15:53:05
 * Version     :  1.0
 *==============================================================================
 */
#include <malloc.h>
#include <pthread.h>
#include <stdio.h>

/* 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 MESSAGE to the log file for the current thread. */
void close_thread_log (void* thread_log);/* Close the log file pointer THREAD_LOG. */
void* thread_function (void* args);

int main ()
{
	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);
	/* Create threads to do the work. */
	for (i = 0; i < 5; ++i)
	{
		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;
}

void write_to_thread_log (const char* message)
{
	FILE* thread_log = (FILE*) pthread_getspecific (thread_log_key);
	fprintf (thread_log, "%s\n", message);
}

void close_thread_log (void* thread_log)
{
	fclose ((FILE*) thread_log);
}

void* thread_function (void* args)
{
	char thread_log_filename[20];
	char wbuf[64]={0};
	FILE* thread_log;
	/* Generate the filename for this thread’s log file. */
	int sf=(int)pthread_self();
	sprintf (thread_log_filename, "thread%d.log", sf);
	sprintf (wbuf, "Thread %d starting", sf);
	/* 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);
	write_to_thread_log (wbuf);
	/* Do work here... */
	return NULL;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值