jeudi 25 juin 2015

Undefined behavior of std::future as return type?

In my case, I use std::future as a return type but get a undefined behavior. The code is below:

#include <future>
#include <iostream>
#include <pthread.h>

std::future<bool> update() {
  int c = 1; 
  //std::cout << "?" << c << std::endl; // debug line
  auto lambda = [&] () -> bool {
    int b = 0; 
    for(int i = 0; i < 10000000; ++i) {
      b += 1; 
    }  
    std::cout << "?" << c << std::endl;
    return c == 1; 
  }; 
  return std::async(std::launch::async, lambda);
}

int main(int argc, char *argv[])
{
  auto f2 = update();
  std::cout << f2.get() << std::endl;
  return 0; 
}

I compiled this piece of code by g++-4.7.2 -std=c++11 test_future.cc -lpthread and get the following output result:

?0
0

But when I uncommented the debug line above, the output became 1(as expected). Besides, if I use std::future as a parameter with update function in stead of return value, I can also get the right output result.

I want to know what's the problem here. The bug of g++ or the bug of the usage? Thanks.

Aucun commentaire:

Enregistrer un commentaire