C++ 库 - <syncstream>



C++20 中的<syncstream> 头文件提供了一种方便的方式来以线程安全的方式管理输出流。随着现代应用程序中多线程的兴起,确保来自不同线程的输出不会相互干扰变得越来越重要。传统的输出流(如 std::cout)不是线程安全的,当多个线程同时尝试写入同一个流时,会导致数据竞争和不可预测的输出。

<syncstream> 头文件通过引入 std::syncbuf 类来解决此问题,该类允许创建同步输出流。这些流确保输出操作是原子的,这意味着当一个线程正在写入同步流时,其他线程会被阻塞,直到操作完成。

包含 <syncstream> 头文件

要在你的 C++ 程序中包含 <syncstream> 头文件,可以使用以下语法。

#include <syncstream>

<span> 头文件的函数

以下是 <span> 头文件中所有函数的列表。

序号 函数及描述
1 operator=

它赋值一个 basic_syncbuf 对象。

2 swap

它交换两个 basic_syncbuf 对象。

3 emit

它以原子方式将整个内部缓冲区传输到包装的 streambuf。

4 get_wrapped

它检索包装的 streambuf 指针。

5 get_allocator

它检索此 basic_syncbuf 使用的分配器。

6 set_emit_on_sync

它更改当前的 emit-on-sync 策略。

7 sync

它根据当前的 emit-on-sync 策略发出或记录挂起的刷新。

8 rdbuf

它获取指向底层 basic_syncbuf 的指针。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

一起刷新多个输出

在以下示例中,我们将把多个输出消息组合成单个刷新。

#include <iostream> #include <syncstream> int main() { std::osyncstream a(std::cout); a << "Hi, " << "Hello, " << "Welcome" << std::endl; return 0; }

输出

以下是上述代码的输出 -

Hi, Hello, Welcome

手动控制刷新

考虑以下示例,我们将使用 flush() 函数手动刷新输出。

#include <iostream> #include <syncstream> #include <chrono> #include <thread> int main() { std::osyncstream a(std::cout); a << "Welcome."; a.flush(); std::this_thread::sleep_for(std::chrono::seconds(3)); a << "Visit Again!" << std::endl; return 0; }

输出

以上代码的输出如下 -

Welcome.Visit Again!
广告