Skip to content

Value::operator<< overload is not thread-safe #43

@camerongivler

Description

@camerongivler

Running the following code produces a segfault:

#include "JsonBox.h"
#include <ctime>
#include <sstream>
#include <chrono>
#include <thread>
#include <future>

int main()
{
    std::srand(std::time(0));
    int numThings = 50;

    std::promise<void> p;
    std::shared_future<void> f = p.get_future().share();

    for(int i = 0; i < numThings; i++) {
        std::thread t([f](){
                JsonBox::Value val;
                val[std::to_string(std::rand())] = std::rand();
                f.get();

                // This code segfaults
                std::cout << val << std::endl;

                // This code is fine
                /*
                std::ostringstream os;
                val.writeToStream(os);
                std::string print = os.str();
                std::cout << print << std::endl;
                */
            });
        t.detach();
    }
    std::this_thread::sleep_for(std::chrono::duration<double>(0.1));
    p.set_value();
    std::this_thread::sleep_for(std::chrono::duration<double>(0.1));
}

The Values that are printed out are all created in different threads/scopes. It seems as though the overload itself is what is causing the segfault. My guess is it has to do with Value.cpp lines

output.rdbuf(&indent);
and
output.rdbuf(indent.getDestination());

This turns out to be very annoying when debugging code from multiple threads.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions