문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top