Mainly for test purposes,
I want to run a member function on a thread.
Endless tries - and still, only error messages,
Please - can anyone explain the cause of the error and some best practices of doing so? Thanks
#include <thread>
#include <iostream>
using namespace std;
class Test {
public:
int x = 1;
int y = 7;
int a() {
for (int i = 1; i < 1000; i++) {
x += y;
cout << "x:" << x << endl;
}
return x;
}
int b() {
for (int i = 1; i < 1000; i++) {
y -= 0.5 * x;
cout << "y:" << y << endl;
}
return y;
}
Test() {
}
Test* run() {
thread(&Test::a, this);
//thread(&Test::b, this);
return this;
}
};
int main()
{
Test* obj = new Test();
obj->run();
return 0;
}
Your std::thread
object lives only until the end of the expression in which it is created as a temporary. When it is destroyed and the thread is still in a joinable state, std::terminate
is called, which aborts your program.
You should store the std::thread
object somewhere (e.g. in the Test
object or in main
or locally in run
) and call .join()
on it at the correct time where you expect the thread to finish (e.g. destructor or before the end of main
or at the end of run
).
Aside from that, if you run the out-commented thread as well, you have data races causing undefined behavior. You may not access non-atomic objects (such as x
and y
) in multiple threads without synchronization if at least one of these accesses is a write.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments