2

I am using c++, and want to do asynchronous programming. I tried the following code:

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

void f(int id) {

  switch (id) {
    case 28: {
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      break;
    }
    case 9: {
      std::async(f, 28); //I am using std::async instead of std::thread because I want to get a return value from it in my real code
      break;
    }
  }

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

int main() {
  f(9);
}

and this prints

Test For 28
Test For 9

(and the entire message gets printed after 1 second) What i want to happen is

Test For 9
Test For 28

(and I want the two messages to be printed 1 second from each other)

then I tried to do it wil 100000 milliseconds, but the same thing happens (except it takes much longer).

is there a reason for this not happening?

this also does not work

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

int f(int id) {

  switch (id) {
    case 28: {
      std::this_thread::sleep_for(std::chrono::milliseconds(100000));
      break;
    }
    case 9: {
      std::future<int> a = std::async(f, 28);
      break;
    }
  }

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

int main() {
  f(9);
}

as it produced the same result

Ank i zle
  • 2,089
  • 3
  • 14
  • 36
  • 1
    This is a common mistake, see the duplicate. The `std::future` returned by `std::async` can't be discarded. – François Andrieux Jun 10 '20 at 20:22
  • Consider the effective lifetime of the temporary `std::future` returned by `std::async` and what its destructor will do. – G.M. Jun 10 '20 at 20:22
  • sorry, that i did not put the `std::future`, but even when I do put it, it does not work properly – Ank i zle Jun 10 '20 at 20:24
  • @Ankizle That doesn't change anything. The code will block whenever the future is destroyed. Whether it's at the end of the expression when you don't store it anywhere, or at the `break`. – François Andrieux Jun 10 '20 at 20:26
  • 1
    Consider this example: https://godbolt.org/z/W4oGs_ – Evg Jun 10 '20 at 20:27

0 Answers0