Quantcast
Viewing latest article 1
Browse Latest Browse All 2

Answer by Miles Budnek for c++ Multi-threading Argument Issues

You are invoking undefined behavior by passing a pointer to a local variable to your threads and allowing the variable to go out of scope before it's used.

C-style arrays are never passed by value. A function declared to take an array type as an argument actually takes a pointer:

void MyClass::MyFunction(std::mutex *dataLock, int sampleIndex, int Id, double srcPoint[3])

is equivalent to

void MyClass::MyFunction(std::mutex *dataLock, int sampleIndex, int Id, double* srcPoint)

In this case, your p array is local to your for loop scope, and it implicitly decays into a pointer to its first element when passed to your thread constructor. As soon as each iteration of your loop completes, p goes out of scope and is destroyed, but your thread still has a pointer to the memory it used to inhabit.

The best option to fix this would be to replace double p[3] with std::array<double, 3> p in your loop and to make MyClass::MyFunction take a parameter std::array<double, 3> srcPoint instead of double srcPoint[3]. Unlike raw C-style arrays, std::array can be passed by value, and implements the copy semantics you expect.


Viewing latest article 1
Browse Latest Browse All 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>