开发者

redirect standard output to a file using multiple thread

开发者 https://www.devze.com 2023-01-24 03:57 出处:网络
I tried to redirect standart output (cout) to a file, for debugging purposes std::ofstream traceFile; traceFile.open(\"c:/path/file.txt\");

I tried to redirect standart output (cout) to a file, for debugging purposes

std::ofstream traceFile;
traceFile.open("c:/path/file.txt");
std::streambuf* fileBuff = traceFile.rdbuf();

std::cout.rdbuf开发者_开发百科(fileBuff);

std::cout << std::unitbuff;

std::cout << "disk is written\n";

But calling cout from a new thread make the code stuck on a mutex. (xmtx.c 39: _Mtxlock()).

Have you got an idea, how i could solve it?

Thank you


This example works fine for me, whilst your test case doesn't. On my machine your code seemed to double free the streambuf from the file, whereas this example swaps it back before the destructors are called.


May be you need to reset cout's streambuf to original.

std::ofstream traceFile;
traceFile.open("c:/path/file.txt");
std::streambuf* fileBuff = traceFile.rdbuf(), *origBuf;

origBuf = cout.rdbuf(); //Save cout's StreamBuf pointer
std::cout.rdbuf(fileBuff); //Set cout's StreamBuf to file's StreamBuf pointer

std::cout << std::unitbuff;

std::cout << "disk is written\n";
cout.rdbuf(origBuf);  //Reset cout's StreamBuf back to original

Also, writing into same file by multiple threads concurrently may not be allowed. That may be reason for the failure of acquisition of mutex.

0

精彩评论

暂无评论...
验证码 换一张
取 消