0

I recently asked this and this question. I wanted to use both answers I got, but when I do so, the std::async gets called synchronously.

#include <thread>
#include <chrono>
#include <iostream>
#include <future>
#include <memory>

typedef struct {

  std::unique_ptr<std::future<int>> a;

} test;

int f(int id) {

  std::future<int> a;

  switch (id) {
    case 28: {
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      break;
    }
    case 9: {
      a = std::async(f, 28);

      test t = test{ std::make_unique<std::future<int>>(std::move(a)) };

      break;
    }
  }

  std::cout << "Test For " << id << std::endl;
  return 0;
}

int main() {
  f(9);
}

I thought that because the std::future did not call the destructor, it would be called asynchronously, but it is not.

I want a result like this

Test For 9
# (after ~1 second)
Test for 28

but again it is doing like so:

# (after ~1 second)
Test For 28
Test For 9

Why is this not working properly?

Ank i zle
  • 2,089
  • 3
  • 14
  • 36
  • You should be passing `std::launch::async` to ensure this runs on a different thread given that your code relies on that. – chris Jun 11 '20 at 00:25

1 Answers1

3

The destructor of t is still called when the scope of the switch exits. You need to declare the scope of t to be the entire function:

int f(int id) {

  test t;         // declare outside switch
  switch (id) {

     // ...
     t = test{ std::make_unique<std::future<int>>(std::move(a)) };

  }
}

Here's a demo.

cigien
  • 57,834
  • 11
  • 73
  • 112