As i said in the title im having an issue while trying to print coordinate values like this while using a std::thread
#include <array>
#include <thread>
struct Vec2
{
int x;
int y;
};
void dostuff2(Vec2 x)
{
std::cout << x.x << x.y << " ";
}
void dostuff(Vec2 Oven[3])
{
for (int i=0; i<3; ++i)
{
dostuff2(Oven[i]);
}
}
int main()
{
Vec2 Oven[3]{ {63,21},{63,22},{63,23} };
std::thread thread_obj(dostuff,std::ref(Oven));
thread_obj.detach();
}
Any ideas why this code isnt working? It was working without me executing the function on a seperate thread..
>Solution :
The main function could end before the thread finishes, meaning the life-time of Oven ends and any references or pointers to it will become invalid.
If you don’t detach the thread (and instead join it) then it should work fine.
Another solution is to use std::array instead, in which case the thread would have its own copy of the array object.
On a side-note, there’s no need for std::ref here, as the dostuff function expects a pointer, not a reference. Which is what plain Oven will decay to.
Plain
std::thread thread_obj(dostuff,Oven);
would work exactly the same, and even have the same problem.