c++ - 控制多线程程序中的输出流
问题描述
我正在尝试控制模拟中的输出打印。它打印了很多输出流信息。这是我如何尝试控制输出流的示例代码。有时我想为每个线程打印信息,有时我不想从线程中打印一次以减少模拟中的系统调用。我通过命令行参数来控制流。争论v
意味着没有指纹。问题是它在整个模拟器中需要很多if
语句。有没有简单的方法来处理这个问题?
#include <iostream>
#include <thread>
void work_to_do_1(char ch)
{
//work for thread 1
if(ch != 'v')
std::cout << "-:Thread 1:-" << std::endl;
}
void work_to_do_2(char ch)
{
if (ch != 'v')
std::cout << "-:Thread 2:-" << std::endl;
}
void work_to_do_3(char ch)
{
if (ch != 'v')
std::cout << "-:Thread 3:-" << std::endl;
}
int main(int argc, char *arg[])
{
std::cout << "You have entered " << argc
<< " arguments:" << "\n";
for (int i = 0; i < argc; ++i)
{
std::cout << arg[i] << "\n";
}
char t = *arg[1];
std::cout << "manager is running" << std::endl;
std::thread t1(work_to_do_1, t);
std::thread t2(work_to_do_2, t);
std::thread t3(work_to_do_3, t);
t1.join();
t2.join();
t3.join();
system("pause");
return 0;
}
解决方案
Make your own nul stream:
struct cnul_t : std::basic_ostream<char> {} cnul;
template<class T> std::ostream& operator<<(cnul_t& os, T const&) { return os; }
And redirect your output to it to ignore it:
#include <ostream>
#include <iostream>
struct cnul_t : std::basic_ostream<char> {} cnul;
template<class T> std::ostream& operator<<(cnul_t& os, T const&) { return os; }
void maybe_log(bool b)
{
std::ostream& out = b == true ? std::cout : cnul;
out << "Hello, World!\n";
}
int main()
{
maybe_log(true); // outputs Hello, World!
maybe_log(false); // no output
}
推荐阅读
- .htaccess - 如何将整个子目录路径重定向到 .htaccess 中的新子目录路径
- python - Pandas 基于另一个单索引数据帧查询多索引数据帧
- batch-file - 使用批处理文件在另一个批处理文件打开的提示符中插入命令
- jmeter - Taurus:使用外部属性文件而不是在 YAML 中指定
- java - org.h2.jdbc.JdbcSQLException:列计数不匹配时
- python - 读取带有数值和缺失数据的熊猫列作为字符串
- vba - Excel 中的 Flash 填充结果为列 - 而不是行
- javascript - 宏JavaScript;在 IF else 语句上循环
- php - Laravel 5.5.42 中的 Cookie(取消)序列化
- python - 将输入文件从 Excel VBA 发送到 Raspberry Pi,而不更改内容