std::osyncstream 输出乱码文本并导致 SEG 故障

std::osyncstream outputs garbled text and causes seg fault

提问人:rm1948 提问时间:1/15/2022 更新时间:1/15/2022 访问量:155

问:

使用 osyncstream 时,此代码会输出垃圾字符,并不总是同步,并且会出现错误。当输出直接到 std::cout 时,输出不同步,但输出良好,不会出现故障。

#include <atomic>
#include <chrono>
#include <iostream>
#include <syncstream>
#include <thread>

std::osyncstream sync_out { std::cout };
//std::ostream& sync_out { std::cout };

void test_ths(int th) {

    while(true) {
        sync_out << "th " << th << " wait 1\n";
//        std::this_thread::sleep_for(std::chrono::milliseconds(30 + 2 * th));
        std::this_thread::sleep_for(std::chrono::milliseconds(30));

        sync_out << "th " << th << " wait 2\n";
//        std::this_thread::sleep_for(std::chrono::milliseconds(30 + 2 * th));
        std::this_thread::sleep_for(std::chrono::milliseconds(30));

        // needed to force output from osyncstream
        sync_out.emit();  // comment out when using std::cout
    }
}
int main() {

    std::jthread t1([] {
        test_ths(1);
    });

    std::jthread t2([] {
        test_ths(2);
    });

    std::jthread t3([] {
        test_ths(3);
    });

    std::jthread t4([] {
        test_ths(4);
    });

    t1.join();
    t2.join();
    t3.join();
    t4.join();
}

说明问题的示例输出。

th 2 wait 1
th th 4 wait 2
3 wait 2
th 1 wait 2
th 2 wait 2
th t 1
th о�ޓ�F�ߓ�F�@FfW��,@���W�th 4 wait 1
th  wait 1
th 2 wait 1
th 3 wait 2
th 4 wait 2
th 2 wait 2
th 3 wait 2
th 1 wait 2
th 2 wait 1
th 4 wait 1
th 3 wait 1
Segmentation fault (core dumped)

sleep_for时间相同时,问题更加明显。注释掉的行会引入一些抖动,这会有所帮助,但问题仍然存在。

当使用 std::cout 时,注释掉,它运行正常。sync_out.emit();

我对 osyncstream 的理解是来自不同线程的输出不应混合,即这就是它的目的。

C++ STL C++20 IOstream

评论


答:

4赞 T.C. 1/15/2022 #1

这不是应该使用的方式。每个线程都需要构造自己的;对自身的访问没有同步。只有 执行的传输是同步的,然后仅与它包装的 streambuf 同步。osyncstreamosyncstreamosyncstreamemit

因此,拥有全球完全没有意义。osyncstream

评论

0赞 rm1948 1/15/2022
谢谢。没有完全理解用法。将 osyncstream 移动到线程中,它工作正常。