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

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();
}} // namespaceint test_syncstream()
{
#ifdef _MSC_VERstd::ofstream file_out1("../../../testdata/output1.txt");std::ofstream file_out2("../../../testdata/output2.txt");
#elsestd::ofstream file_out1("testdata/output1.txt");std::ofstream file_out2("testdata/output2.txt");
#endifif (!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.lryc.cn/news/468804.html

相关文章:

  • 判断特定时间点开仓的函数(编程技巧)
  • 如何新建一个React Native的项目
  • 学习--图像信噪比
  • 【2024CANN训练营第二季】使用华为云体验AscendC_Sample仓算子运行
  • 使用 NumPy 和 Matplotlib 实现交互式数据可视化
  • TCP 攻击为何在 DDoS 攻击中如此常见
  • 未来汽车驾驶还会有趣吗?车辆动力学系统简史
  • LCD手机屏幕高精度贴合
  • 15_卸载操作
  • ONLYOFFICE 文档8.2版本已发布:PDF 协作编辑、改进界面、性能优化等更新
  • redis的string是怎么实现的
  • 基于STM32设计的智能婴儿床(华为云IOT)(244)
  • html+css+js实现Notification 通知
  • 【Linux】拆分详解 - 常见指令和权限理解
  • UniHttp 框架,请求http接口
  • C++20中头文件ranges的使用
  • 设计一个html+css+js的注册页,对于注册信息进行合法性检测
  • 语音识别——使用Vosk进行语音识别
  • element ui中el-image组件查看图片的坑
  • LabVIEW水质监测系统
  • SpringMVC之 文件上传和下载
  • LeetCode Hot 100:二分查找
  • 打包方式-jar和war的区别
  • 【论文+源码】基于spring boot的垃圾分类网站
  • 【C++ STL 模板类】pair 键值对
  • paddleocr使用FastDeploy 部署工具部署 rknn 模型
  • Apple Vision Pro市场表现分析:IDC最新数据揭示的真相
  • Mybatis-04.入门-JDBC
  • 拥抱云开发的未来:腾讯云数据库、云模板与AI智能化的应用场景探索
  • 新手铲屎官求推荐,噪音低的宠物空气净化器应该用哪款