BDE 4.14.0 Production release
Loading...
Searching...
No Matches
bslstl_osyncstream

Detailed Description

Outline

Purpose

Provide a C++20-compatible basic_osyncstream class template.

Classes

Canonical header: bsl_syncstream.h

See also
bslstl_syncbuf

Description

This component is for internal use only. Please include <bsl_syncstream.h> instead.

This component defines a class template, bsl::basic_osyncstream, that is a convenience wrapper for bsl::basic_syncbuf. It provides a mechanism to synchronize threads writing to the same stream, or more precisely, to the same streambuf. It's guaranteed that all output made to the same final destination buffer will be free of data races and will not be interleaved or garbled in any way, as long as every write to that final destination buffer is made through (possibly different) instances of bsl::basic_syncbuf.

Types bsl::osyncstream and bsl::wosyncstream are aliases for bsl::basic_osyncstream<char> and bsl::basic_osyncstream<wchar_t>, respectively.

Usage

This section illustrates intended use of this component.

In a multi-threaded environment attempts to write from different threads to one ostream "may result in a data race", according to the ISO C++ Standard. Concurrent access to the special synchronized iostream objects, like cout, cerr, etc, does not result in a data race, but output characters from one thread can interleave with the characters from other threads still. osyncstream solves both problems: prevents data races and characters interleaving.

Example 1: Using osyncstream

The following example demonstrates concurrent printing of a standard STL container of values that can be streamed out. The elements are separated by comma and the whole sequence is enclosed in curly brackets. Note that this example requires at least C++11.

template <class t_CONTAINER>
void printContainer(bsl::ostream& stream, const t_CONTAINER& container)
// Print elements of the specified 'container' to the specified
// 'stream' in a multi-threaded environment without interleaving with
// output from another threads.
{
bsl::osyncstream out(stream);
out << '{';
bool first = true;
for(auto& value : container) {
if (first) {
first = false;
}
else {
out << ", ";
}
out << value;
}
out << '}';
} // all output is atomically transferred to 'stream' on 'out' destruction
Definition bslstl_osyncstream.h:154

Now this function can safely be used in a multi-threaded environment:

int main()
{
bsl::vector<int> container1 = {1, 2, 3};
bsl::vector<double> container2 = {4.0, 5.0, 6.0, 7.0};
bsl::thread thread1{[&]{ printContainer(bsl::cout, container1); }};
bsl::thread thread2{[&]{ printContainer(bsl::cout, container2); }};
thread1.join();
thread2.join();
}
Definition bslstl_vector.h:1025