I've been trying to use the std::thread library (in gcc) to multithread some parts of my code. I've used threads before, but I'm not sure how to do this using std::thread. I have a class that has a few methods, each method needs to be able to run on a thread and have access to the classes' member variables (threads do not access the same member variables, so no need for mutexes, yet).
Now I can run the member methods in the thread, but i cannot get access to the member variables, everytime I do, the program crashes. Here is a quick test bit of code of what I essentially need to do.
So I have a member variable, int test, that my thread needs access too. But if I try to access the variable, the program crashes. I tried passing a pointer to the object to the thread function so I could access the variable by pointer->test, but that didn't work either. Anyone know of a way I can tackle this?
Code: Select all
#include <stdio.h>
#include <thread>
#include <time.h>
#include <unistd.h>
#include <iostream>
class background
{
public:
int test;
//VeryLargeDataStructure LargeData;
background()
{
test = 0;
};
void changeTest(int newt)
{
test = newt;
}
void doWork(int loop)
{
// perform some heavy computation on test and LargeData
std::cout <<"Thread started\n";
for(int i=0;i<loop;i++)
{
std::cout << "Doing work: " << loop << "\n";
for(int j=0;j<loop;j++)
{
if( i % j == 0 )
{
// This line causes problems.
test++;
}
}
usleep(10);
}
};
};
int main()
{
background * g = new background();
// How do i run g->doWork(5000) in a background thread, and also have access to g's member variables?
std::thread t(&background::doWork, g , 5000);
t.join();
std::cout << "waiting\n";
return 0;
};