Skip to content

Instantly share code, notes, and snippets.

@IMelker
Last active Apr 14, 2020
Embed
What would you like to do?
ScopePrinter to exchange printf and make it multithread
#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