Reputation: 35
I am quite new to c++ and I'm not really understanding how to overcome this. In essence, I have a Base class with 2 derived classes. I have a fourth 'processing' class.
I need to create three threads, with the two derived classes producing data and 'processing' class doing its own calculations based on this data.
I want the two derived classes to put the results in a struct, and the processing class access that struct.
Where I'm having trouble is in beginning the thread, since I need to give it the object for the derived class and the object for the data struct and it's just not working. Here is more or less what I have.
#include <cstdio>
#include <iostream>
#include <random>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <chrono>
#include <ctime>
#define _USE_MATH_DEFINES
#include <math.h>
#include <time.h>
#include <iostream>
#include <thread>
#include <atomic>
#include <vector>
#include <mutex>
using namespace std;
struct Test_S
{
vector<double> test_vector1;
vector<double> test_vector2;
mutex test_mtx;
};
class Base
{
public:
Base();
void domath() {cout<<"base function"<<endl;}
int i;
};
class Derived1 : public Base
{
public:
Derived1();
void domath1()const {test_s.test_vector1.push_back(1);}
};
class Derived2 : public Base
{
public:
Derived2();
void domath2()const {test_s.test_vector2.push_back(2);}
};
int main( int argc, char ** argv )
{
Base base;
Derived1 derived1;
Derived2 derived2;
Test_S test_s;
std::thread t1(&Derived1::domath1, &test_s);
std::thread t2(&Derived2::domath2, &test_s);
t1.join();
t2.join();
}
Upvotes: 1
Views: 2141
Reputation: 9602
The constructor of std::thread
you're using is taking a pointer to a member function therefore the second argument needs to be an instance of the class, which is necessary to call the member function.
In the case of t1
and t2
the second argument can be &derived
and &derived2
, respectively.
Regarding the test_s
used by the functions passed to std::thread
, you'll need a way to get that state to those classes. You could pass the state as a parameter to the function being passed to std::thread
.
Just for illustration:
void domath1(Test_S* test_s) const { test_s->test_vector1.push_back(1); }
...
std::thread t1(&Derived1::domath1, &derived1, &test_s);
Upvotes: 1