Skip to content

Instantly share code, notes, and snippets.

@IMelker
Last active April 14, 2020 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IMelker/ded36c21f557b266888d714ed66414e3 to your computer and use it in GitHub Desktop.
Save IMelker/ded36c21f557b266888d714ed66414e3 to your computer and use it in GitHub Desktop.
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