Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this function not print the coordinates properly?

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..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading