std::basic_osyncstream

std::basic_osyncstream (동기화 출력 스트림)

std::basic_syncbuf를 위한 편의 래퍼 클래스 템플릿이에요. 같은 스트림에 쓰는 스레드들을 동기화하는 메커니즘을 제공해요. C++20부터 있어요.

출처: cppreference

본문

<syncstream> 헤더에 정의돼 있어요.

template<
    class CharT,
    class Traits = std::char_traits<CharT>,
    class Allocator = std::allocator<CharT>
> class basic_osyncstream : public std::basic_ostream<CharT, Traits>;

클래스 템플릿 std::basic_osyncstreamstd::basic_syncbuf를 위한 편의 래퍼예요. 같은 스트림에 쓰는 스레드들을 동기화하는 메커니즘을 제공해요. 명명된 변수로 쓸 수 있어요.

{
    std::osyncstream synced_out(std::cout); // synchronized wrapper for std::cout
    synced_out << "Hello, ";
    synced_out << "World!";
    synced_out << std::endl; // flush is noted, but
    synced_out << "and more!\n"; // still within the same block
} // block ends, all output is transferred to std::cout

공통 문자 타입 typedef

  • std::osyncstreamstd::basic_osyncstream<char>
  • std::wosyncstreamstd::basic_osyncstream<wchar_t>

멤버 함수

  • (constructor) — osyncstream을 생성해요.
  • get_wrapped — 감싼 스트림 버퍼를 돌려줘요.
  • rdbuf — 기반 syncbuf에 접근해요.
  • emit — 출력을 감싼 버퍼에 전달해요.
  • operator= — 이동 대입(내부 버퍼 재설정).

예제

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

int main()
{
    std::vector<std::thread> threads;
    for (int i = 0; i < 4; ++i)
        threads.emplace_back([i] {
            std::osyncstream(std::cout) << "thread " << i << " writes\n";
        });
    for (auto& t : threads) t.join();
}

더 알아보기 (Learn more)

cppreference