多线程调试信息的打印

多线程程序由于输出混乱无法分辨每个线程进行到程序的哪一步给多线程程序的调试带来很大困难。

 

写了一个程序只要在每个线程里面加入这个类,调用这个类的print()方法即可以把每个线程的输出保存到一个自己的文件里,文件名为线程号.txt。

 

print()方法主要是对vfprintf的包装

 

RTFSC:

thread_print.h

#ifndef _THREAD_PRINT_ #define _THREAD_PRINT_ #include #include #include #include #include using namespace std; class Thread_print { private: int tid; string int2string(int); FILE* fp; public: Thread_print(int); ~Thread_print(); void print(const char*, ...); }; #endif

thread_print.cpp

#include "thread_print.h" #include #include #include Thread_print::Thread_print(int id):tid(id) { string filename = int2string(tid)+".txt"; if((fp = fopen(filename.c_str(), "a+")) == NULL) { printf("thread_print open failed/n"); exit(1); } } Thread_print::~Thread_print() { fclose(fp); } void Thread_print::print(const char* fmt, ...) { va_list args; va_start(args, fmt); fseek(fp, 0, SEEK_END); vfprintf(fp, fmt, args); fflush(fp); va_end(args); return; } string Thread_print::int2string(int n) { stringstream newstr(stringstream::in | stringstream::out); newstr << n; return newstr.str(); }

 

test.cpp

#include "thread_print.h" #include #include void* thread_work(void* arg) { int tid = (int)arg; Thread_print tp(tid); int i = 100; char * str = "this is a string"; double d = 3.14; tp.print("hello/nint : %d/nstring : %s/ndouble : %f/n", i, str, d); } int main() { pthread_t thread; void* status; pthread_create(&thread, NULL, thread_work, (void*)1); sleep(3); pthread_join(thread, &status); return 0; }

你可能感兴趣的:(多线程调试信息的打印)