0

Can someone tell me what is wrong with these pieces of code :

std::vector<double> vUp;
QFuture<double> tu, td;
foreach(boost::tie(tu, td), boost::combine(Up_corr.futures(), Down_corr.futures()))
{
   vUp.push_back((tu.result()+td.result())*0.5);
 }

I got the following error at run time:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x51)

The Up_corr and Down_corr are both QFutureSynchronizer and are well defined as the third methods present in this thread is working. Also, before passing through the above loop, I am waiting that both, Up_corr and Down_corr QtConcurent::run are finished.

This variant of the code is also not working

std::vector<double> vUp;
QList< QFuture<double> >::const_iterator tu   = Up_corr.futures().cbegin();
QList< QFuture<double> >::const_iterator td = Down_corr.futures().cbegin();
for(size_t iCh = 0; iCh < 32; iCh++)
{
     vUp.push_back((tu->result()+td->result())*0.5);
     tu++;
     td++;
}

It gives the same error when trying to access tu->result() or td->result().

The only method which is working is:

std::vector<double> v1;
std::vector<double> v2;

foreach(QFuture<double> thread, Up_corr.futures())
       v1.push_back(thread.result());
foreach(QFuture<double> thread, Down_corr.futures())
       v2.push_back(thread.result());

for(size_t iCh = 0; iCh < 32; iCh++)
       vUp.push_pack((v1[iCh]+v2[iCh])*0.5);

Why is the last one working while the two other failed with BAD ACCESS?

The last methods, which is working, is not optimal: to fill one vector, I will need three loops. For 32 elements it isn't a big deal, but, I will also need to deal with List> of 2k elements and reducing timing is my objective.

Engineero
  • 12,340
  • 5
  • 53
  • 75

1 Answers1

0

I don’t know the foreach macro but assuming it is similar to range-based for it keeps the result of futures() alive. The other variations use this result as part of the expression and then let it die: only a temporary bound directly to a const& or to a && is kept alive. Other temporaries used in an expression are destroyed at the end of the full expression. You may want to try something like

// ...
auto&& ucf = Up_corr.futures();
auto&& dcf = Down_corr.futures();
foreach(boost::tie(tu, td), boost::combine(ucf, dcf))
{
    vUp.push_back((tu.result()+td.result())*0.5);
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • Thanks very much, this indeed solve my problem. Still did not really understand why the second variant of my code does not work initially. Now that variant 1 is fully operational, I will go for it as its seems to me that it will be the more efficient in time. Thanks again – William GILLARD Dec 15 '17 at 14:35