Last active
April 14, 2020 10:00
-
-
Save IMelker/ded36c21f557b266888d714ed66414e3 to your computer and use it in GitHub Desktop.
ScopePrinter to exchange printf and make it multithread
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<string> | |
#include<iostream> | |
class ScopePrinter { | |
public: | |
template<typename STR> | |
explicit ScopePrinter(STR&& init, std::ostream& stream = std::cout) | |
: stream(stream), | |
msg(std::forward<STR>(init)) { | |
msg.append(":\t"); | |
} | |
~ScopePrinter() { | |
dump(); | |
} | |
void f(const char *format, ...) { | |
va_list ap; | |
va_start(ap, format); | |
char str[256] = {}; | |
vsnprintf(str, 256, format, ap); | |
va_end(ap); | |
this->msg.append(str); | |
this->msg.append(" "); | |
} | |
void dump() { | |
{ | |
std::lock_guard lg(this->streamMutex); | |
this->stream << msg << std::endl; | |
} | |
msg.clear(); | |
} | |
private: | |
std::ostream& stream; | |
std::string msg; | |
std::mutex streamMutex; | |
}; | |
int main() { | |
ScopePrinter print(__FUNCTION__, std::cerr); | |
print.f("ptr="%p", &print); | |
if(true) | |
print.f("always true"); | |
else | |
print.f("still making one line"); | |
} // <-- will be printed to std::cerr there. | |
// std::cerr << "main: ptr=0x* always true"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment