当前位置: 首页 > article >正文

C++20中头文件syncstream的使用

      <syncstream>是C++20中新增加的头文件,提供了对同步输出流的支持,即在多个线程中可安全地进行输出操作,此头文件是Input/Output库的一部分。包括:

      1.std::basic_syncbuf:是std::basic_streambuf的包装器(wrapper),它将输出累积在其自己的内部缓冲区中,并在销毁时以及明确请求时将其全部内容自动传输到包装的缓冲区,以便它们显示为连续的字符序列。此类模板主要用于创建与多线程程序无缝协作的自定义流类。如果多个线程试图同时写入同一个流,std::basic_syncbuf将确保每个线程的输出都以正确的顺序写入流,而不会出现任何交错。

using syncbuf  = basic_syncbuf<char>;
using wsyncbuf = basic_syncbuf<wchar_t>;

      2.std::basic_osyncstream:是std::basic_syncbuf的便捷包装器。它提供了一种机制来同步写入同一流的线程。

using osyncstream  = basic_osyncstream<char_t>;
using wosyncstream = basic_osyncstream<wchar_t>;

      测试代码如下:

namespace {

void func1(int id, std::ostream& sync_out)
{
	std::osyncstream sync_stream(sync_out);
	sync_stream << "thread " << id << " is running" << std::endl;
}

void func2(int id, std::ostream& out)
{
	out << "thread " << id << " is running" << std::endl;
}

void sync(std::ofstream& file_out)
{
	std::syncbuf sync_buf(file_out.rdbuf());
	std::ostream sync_out(&sync_buf);

	constexpr int num_threads{ 10 };
	std::vector<std::thread> threads;

	for (int i = 0; i < num_threads; ++i)
		threads.emplace_back(func1, i, std::ref(sync_out));

	for (auto& t : threads)
		t.join();
}

void common(std::ofstream& file_out)
{
	constexpr int num_threads{ 10 };
	std::vector<std::thread> threads;

	for (int i = 0; i < num_threads; ++i)
		threads.emplace_back(func2, i, std::ref(file_out));

	for (auto& t : threads)
		t.join();
}

} // namespace

int test_syncstream()
{
#ifdef _MSC_VER
	std::ofstream file_out1("../../../testdata/output1.txt");
	std::ofstream file_out2("../../../testdata/output2.txt");
#else
	std::ofstream file_out1("testdata/output1.txt");
	std::ofstream file_out2("testdata/output2.txt");
#endif

	if (!file_out1 || ! file_out2) {
		std::cerr << "fail to open file for writing" << std::endl;
		return -1;
	}

	sync(file_out1);
	common(file_out2);

	file_out1.close();
	file_out2.close();
	return 0;
}

      执行结果如下图所示:每次输出并不完全一致:output2.txt中输出是乱的,而output1.txt中的输出是正常的

      GitHub:https://github.com/fengbingchun/Messy_Test


http://www.kler.cn/news/365285.html

相关文章:

  • 企业数字化转型建设方案(数据中台、业务中台、AI中台)
  • 基于Python+SQL Server2008实现(GUI)快递管理系统
  • Oracle 19c RAC删除多余的PDB的方式
  • webpack面试笔记(一)
  • nginx的配置
  • Android 图片相识度比较(pHash)
  • JavaScript 有哪些学习资源
  • Rust使用config加载Toml配置文件
  • leetcode-75-颜色分类
  • 为Windows Terminal 配置zsh + Oh-My-Zsh!
  • 探索 SVG 创作新维度:svgwrite 库揭秘
  • 力扣80:删除有序数组中重复项
  • vue2+elementui日期选择器
  • UI 提供的 progress-step 要怎么实现?
  • 如何使用gitlab切换分支
  • 材质变体 PSO学习笔记
  • Excel重新踩坑3:条件格式;基本公式运算符;公式中的单元格引用方式;公式菜单栏其他有用的功能说明;
  • SSH 的 N 大黑科技玩法
  • 力扣 困难 52.N皇后II
  • 线性可分支持向量机的原理推导 9-28支持向量机优化中的可行性条件 公式解析
  • mysql的卸载与安装
  • 论文翻译 | A Prompt Pattern Catalog to Enhance Prompt Engineering with ChatGPT (下)
  • 【Javaee】网络原理—TCP协议的核心机制
  • 智能园艺:Spring Boot植物健康系统
  • Ubuntu 16上安装Go
  • 【数据分享】全国科技-产品质量国家监督抽查(1995-2021年)