GeezerVison is showing cpprefjp.github.io — std::basic_osyncstream - cpprefjp C++日本語リファレンス
最終更新日時:
2026年01月08日 20時45分05秒 (JST)
yoh
が更新
履歴
編集
class template
<syncstream>
std:: basic_osyncstream (C++20)
namespace std {
template < class charT , class traits , class Allocator >
class basic_osyncstream : public basic_ostream < charT , traits > { ... };
using osyncstream = basic_osyncstream < char > ;
using wosyncstream = basic_osyncstream < wchar_t > ;
}
概要
同じストリームへアトミックに出力するメカニズムを提供する。
エイリアス
説明
対応バージョン
osyncstream
basic_osyncstream<char>
C++20
wosyncstream
basic_osyncstream<wchar_t>
C++20
メンバ
基底クラスである basic_ostream も参照のこと。
メンバ関数
構築・破棄
割り当て
その他メンバ関数
メンバ型
例
#include <iostream>
#include <syncstream>
#include <thread>
void thread1 ()
{
{
std :: osyncstream bout { std::cout };
bout << "Hello, " ;
bout << "World!" ;
bout << std::endl ; // フラッシュがノートされる
bout << "and more! \n " ;
} // 文字が転送され、cout はフラッシュする
}
void thread2 ()
{
// 同じバッファに行われる出力は、異なる std::basic_osyncstream(std::basic_syncbuf) の
// インスタンスからでも、アトミックに出力されることが保証される
std :: osyncstream ( std::cout ) << "Goodbye, " << "Planet!" << '\n' ;
}
int main ()
{
std::thread th1 ( thread1 );
std::thread th2 ( thread2 );
th1 . join ();
th2 . join ();
}
出力例
thread1 の処理が先行した場合。ただし、各出力は連続したシーケンスとなるように、アトミックに行われることが保証される。
Hello, World!
and more!
Goodbye, Planet!
間違った使用の例
std::basic_osyncstreamのオブジェクトはストリーム出力をアトミックにしたいスレッド毎に持つ必要がある。1つのstd::basic_osyncstreamのオブジェクトを複数のスレッドで共有して使用してしまうと、出力は競合する。
#include <iostream>
#include <syncstream>
#include <thread>
// 1つのosyncstream を複数スレッドで共有してしまうと出力の競合が起こる
std :: osyncstream bout { std::cout };
void thread1 ()
{
{
bout << "Hello, " ;
bout << "World!" ;
bout << std::endl ;
bout << "and more! \n " ;
}
}
void thread2 ()
{
bout << "Goodbye, " << "Planet!" << '\n' ;
}
int main ()
{
std::thread th1 ( thread1 );
std::thread th2 ( thread2 );
th1 . join ();
th2 . join ();
}
出力例
Hello, World!
aGoodbye, Planet!
バージョン
言語
処理系
関連項目
参照