首页 > 解决方案 > 在 switch 语句中同步调用 C++ std::async

问题描述

我正在使用 c++,并且想做异步编程。我尝试了以下代码:

#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);
}

这打印

Test For 28
Test For 9

(整条消息在 1 秒后打印)我想要发生的是

Test For 9
Test For 28

(我希望这两条消息彼此相隔 1 秒打印)

然后我尝试在 100000 毫秒内完成,但同样的事情发生了(除了它需要更长的时间)。

这有没有发生的原因?

这也行不通

#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);
}

因为它产生了相同的结果

标签: c++asynchronous

解决方案


推荐阅读