Search code examples
c++g++c++20

Why my stringstream can't work with jthread?


I want to write an integer to a stringstream in another thread. I tried to do that in a jthread, but the stringstream seems not getting anything. If I turn to use thread, everything works well. Would you please help me about why this problem happens, and is there any way to analyze problems like this?

Here's an example piece of code, I tried to write integers to stringstream inside a jthread in the 2nd and 3rd blocks, but it didn't work. Writing integers to stringstream inside a thread instead, in the 4th and 5th blocks can work.

#include <sstream>
#include <thread>
using namespace std;

int main()
{
    // write to stringstream
    stringstream sout1;
    sout1<<1;
    cout<<sout1.str()<<endl;

    // write to stringstream in jthread, capture by reference
    stringstream sout2;
    jthread t2([&sout2]{
        sout2<<2;
    });
    cout<<sout2.str()<<endl;

    // write to stringstream in jthread, passing by parameter as pointer
    stringstream sout3;
    jthread t3([](stringstream* sout3){
        *sout3<<3;
    }, &sout3);
    cout<<sout3.str()<<endl;

    // write to stringstream in thread, capture by reference
    stringstream sout4;
    thread t4([&sout4](){
        sout4<<4;
    });
    t4.join();
    cout<<sout4.str()<<endl;

    // write to stringstream in thread, passing in parameter as pointer
    stringstream sout5;
    thread t5([](stringstream* sout5){
        *sout5<<5;
    }, &sout5);
    t5.join();
    cout<<sout5.str()<<endl;
}

Output:

1


4
5

Solution

  • to have valid data in the stringstream you must join() the thread before you read from the stringstream, this doesn't change between thread and jthread.

    jthread automatically join() the thread in the destructor, this happens at the end of scope while thread instead calls std::terminate() at the end of scope if it wasn't joined, this is the main difference.