Namespaces
Variants

std::basic_osyncstream<CharT,Traits,Allocator>::basic_osyncstream

From cppreference.com
Revision as of 16:58, 24 October 2021 by 93.42.71.126 (talk) (Added example)
 
 
 
 
basic_osyncstream( streambuf_type* buf, const Allocator& a );
(1)
explicit basic_osyncstream( streambuf_type* buf );
(2)
basic_osyncstream( std::basic_ostream<CharT, Traits>& os, const Allocator& a );
(3)
explicit basic_osyncstream( std::basic_ostream<CharT, Traits>& os );
(4)
basic_osyncstream( std::basic_osyncstream&& other ) noexcept;
(5)

Constructs new synchronized output stream

1-4) constructs the private member std::basic_syncbuf using the buffer and the allocator provided, and initializes the base class with a pointer to the member std::basic_streambuf.
5) Move constructor. Move-constructs the std::basic_ostream base and the std::basic_syncbuf member from the corresponding subobjects of other, then calls set_rdbuf with the pointer to the newly-constructed underlying std::basic_syncbuf to complete the initialization of the base. After this move constructor, other.get_wrapped() returns nullptr and destruction of other produces no output.

Parameters

buf - pointer to the std::basic_streambuf that will be wrapped
os - reference to a std::basic_ostream, whose rdbuf() will be wrapped
a - the allocator to pass to the constructor of the member std::basic_syncbuf
other - another osyncstream to move from

Example

#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <syncstream>
#include <thread>
#include <vector>

void worker(const std::string &id, std::ostream &os) {
  for(int i = 1; i <= 40; ++i) {
    os << '[' << id << ']'
       << " line " << std::setw(2) << i << ':'
       << " very long line"
       << " that should cause some interference"
       << " on output " << std::endl;
  }
}

int main() {
  using namespace std::string_literals;

  auto w1 = std::thread{worker, "no sync 1"s, std::ref(std::cout)};
  auto w2 = std::thread{worker, "no sync 2"s, std::ref(std::cout)};

  w1.join();
  w2.join();

  auto scout1 = std::osyncstream{std::cout};
  auto scout2 = std::osyncstream{std::cout};

  w1 = std::thread{worker, "sync 1", std::ref(scout1)};
  w2 = std::thread{worker, "sync 2", std::ref(scout2)};

  w1.join();
  w2.join();

  return EXIT_SUCCESS;
}

See also

constructs a basic_syncbuf object
(public member function of std::basic_syncbuf<CharT,Traits,Allocator>) [edit]