C++ Library - <syncstream>



The <syncstream> header in C++20, provides a convenient way to manage output streams in a thread safe manner. With the rise of multithreading in modern applications, ensuring that output from different threads does not interfere with each other has become important. Traditional output streams (like std::cout) are not thread-safe, which lead to data races and unpredictable output when multiple threads attempt to write the same stream simultaneously.

The <syncstream> header addresses this by introducing the std::syncbuf class, which allows to create a synchronized output streams. These streams ensure that output operations are atomic, meaning that when one thread is writing to a synchronized stream, other threads are blocked from writing untill the operation is complete.

Including <syncstream> Header

To include the <syncstream> header in your C++ program, you can use the following syntax.

 #include <syncstream> 

Functions of <span> Header

Below is list of all functions from <span> header.

Sr.NoFunctions & Description
1operator=

It assigns a basic_syncbuf object.

2swap

It swaps two basic_syncbuf objects.

3emit

It atomically transmits the entire internal buffer to the wrapped streambuf.

4get_wrapped

It retrieves the wrapped streambuf pointer.

5get_allocator

It retrieves the allocator used by this basic_syncbuf.

6set_emit_on_sync

It changes the current emit-on-sync policy.

7sync

It either emits, or records a pending flush, depending on the current emit-on-sync policy.

8rdbuf

It obtains a pointer to the underlying basic_syncbuf.

Flushing Multiple Outputs Together

In the following example, we are going to combine the multiple output messages into a single flush.

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

Output

Following is the output of the above code −

 Hi, Hello, Welcome 

Manual Control of Flushing

Consider the following example, where we are going to manually flush the output using the flush() function.

 #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; } 

Output

Output of the above code is as follows −

 Welcome.Visit Again! 
Advertisements
close