Killrazor
Killrazor

Reputation: 7184

Read/Write information to class in another thread

maybe I'm completely lost but I'm trying to learn threads in c++ and this code is not working quite well:

The relevant code is

TEST_F(TestSimulation, run_could_be_closed) {
    sim::Simulation simulation;
    std::thread thread(simulation);
    while (simulation.getCount() < 15000) {
        // wait
    }
    simulation.dispose();
}
void sim::Simulation::run() {  
    while (isRunning) {
        std::cout << "Processing information" << std::endl;
        count++;
    }
}

void sim::Simulation::dispose() {
    isRunning = false;
}

int sim::Simulation::getCount() {
    return count;
}
void sim::Simulation::operator()() {
    init();
    run();
}

Seems that the Thread class creates a copy of the object sent as parameter, so when I call simulation.getCount() in main thread, it always returns 0.

When I try to pass as reference std::thread thread(&simulation); I get an error

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/thread:336:5: error: attempt to use a deleted function
    __invoke(_VSTD::move(_VSTD::get<1>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...);

What I want is to be able to writing and reading data to the object while is running inside the thread. Is this the way to go?

Upvotes: 0

Views: 151

Answers (2)

devin
devin

Reputation: 36

std::thread thread(&simulation); thread initialization error

Here is a similar example

class Simulation {
public:
    Simulation() : count(0), isRunning(true) {}

    void Simulation::run() {
        while (isRunning) {
            std::cout << "Processing information" << std::endl;
            count++;
        }
    }

    void Simulation::dispose() { isRunning = false; }

    int Simulation::getCount() { return count; }

private:
    int count;
    bool isRunning;
}

int mian() {

    Simulation simulation;
    std::thread thread(&Simulation::run, &simulation);
    while (simulation.getCount() < 15) {
        // wait
    }
    simulation.dispose();
    simulation.join();
    cout << simulation.getCount() << endl;

    return 0;
}

Upvotes: 1

salchint
salchint

Reputation: 391

The example section of https://en.cppreference.com/w/cpp/thread/thread/thread demonstrates how to pass a class' member function and a reference to an instance of that class to a std::thread. See std::thread t5(&foo::bar, &f); in that sample coding.

This way you should be able to share one instance of sim::Simulation from your sample coding between the two threads. BUT this will open doors for all kinds of synchronization problems and races on the shared object/fields. So take care when you go beyond sharing just an count, which I presume is from an atomicly writable type.

Upvotes: 1

Related Questions