C++20 std::basic_syncbuf
Last Updated :
04 Oct, 2023
In C++, the std::basic_syncbuf class template is part of the Standard Library, used for creating custom stream buffers. This class template is primarily intended for use in creating custom stream classes that work seamlessly with multithreaded programs.
This means that if multiple threads are trying to write to the same stream at the same time, std::basic_syncbuf will make sure that the output from each thread is written to the stream in the correct order, without any interleaving.
Syntax of std::basic_syncbuf
std::basic_syncbuf buffer_name ( buf, allocator )
where
- buf: buffer
- allocator: custom allocator
std::basic_syncbuf Methods
The following are some common member methods of std::basic_syncbuf:
- emit(): This method flushes the content of the object’s internal buffer to the wrapped stream buffer.
- get_wrapped(): The method returns the wrapped stream buffer.
- get_allocator(): The method returns the allocator used to manage the basic_syncbuf object’s internal buffer.
- set_emit_on_sync(bool): Sets whether the contents of the ‘basic_syncbuf` object’s internal buffer should be flushed to the wrapped stream buffer on sync.
Example of std::basic_syncbuf
Example 1: Implementation of std::basic_syncbuf
C++
#include <iostream>
#include <fstream>
#include <syncstream>
using namespace std;
int main()
{
basic_syncbuf< char > synced_buf(ofstream( "output.txt" ));
osyncstream synced_out(synced_buf);
synced_out << "Hello, World!" ;
synced_out << endl;
thread t1([&synced_out] {
synced_out << "Thread 1!" << endl;
});
thread t2([&synced_out] {
synced_out << "Thread 2!" << endl;
});
t1.join();
t2.join();
return 0;
}
|
Output
Hello, World!
Thread 1!
Thread 2!
Explanation of the above program:
The program creates a synchronized output stream for a file stream called output.txt. It then writes the message “Hello, World!” to the stream. Next, it creates two threads that will write the messages “Thread 1!” and “Thread 2!” to the stream concurrently. Finally, it joins the threads and returns.
Example 2:
C++
#include <iostream>
#include <syncstream>
using namespace std;
int main()
{
basic_syncbuf< char > buffer;
buffer << "Program 2\n" ;
buffer.emit();
buffer.get_wrapped()->close();
return 0;
}
|
Output
Program 2
Key Points about std::basic_syncbuf
There are certain Key points that can be derived about basic_syncbuf in C++ 20 as mentioned below:
- It is a template class that takes two template parameters.
- It provides member functions for synchronization, which is crucial for ensuring thread safety when working with streams in a multithreaded environment.
- The constructors and destructors are also provided, allowing us to specify the buffer size when needed.
Share your thoughts in the comments
Please Login to comment...