I have the following function:
void MyClass::myFunc(cv::OutputArray dst) const {
cv::Mat result;
...
dst.assign(result);
}
If I run it like this:
cv::Mat result;
myFunc(result);
otherFunc(result);
It works fine and otherFunc recieves result modified by myFunc.
But if I use std::async like this:
cv::Mat result;
auto resultFuture = std::async(&MyClass::myFunc, this, result);
resultFuture.wait();
otherFunc(result);
otherFunc receives empty result. What am I doing wrong?
The root cause is that passing arguments by reference (&) to a function to run via
std::asyncis problematic. You can read about it here: Passing arguments to std::async by reference fails (in your case there is no a compilation error, but the link explains the issue in general).And in your case you use
cv::OutputArraywhich is defined in opencv as a refernce type:I assume you wanted the reference semantics, since you expected your
resultobject to be updated bymyFunc.The solution is to use
std::ref.But since the
resultobject you pass is acv::Mat, it preferable and more straightforward thatmyFuncwill receive acv::Mat&.I also managed to produce a solution using a
cv::OutputArray, but it requires an ugly cast (in addition to thestd::ref). It works fine on MSVC, but I am not sure it is will be generally valid.Below is the code demostrating these 2 options. I recomend to use the 1st approach if you can. You can call
otherFunc(result);at the point where I print the dimensions ofresultafter it is initialized.