我正在尝试使用std::async
和std::future
在我的应用程序中创建一个后台工作的守护进程。我的行为似乎表明我根本没有异步运行!
我编译了一小段代码来演示什么对我不起作用:
#include <cstdio>
#include <future>
#include <chrono>
class AsyncTest {
public:
void run() {
printf("Entering run()\n");
std::this_thread::sleep_for(std::chrono::seconds(10));
printf("Exiting run()\n");
}
void start() {
printf("Starting daemon...\n");
std::async(std::launch::async, &AsyncTest::run, this);
printf("Daemon started\n");
}
};
int main(int argc, char *argv[])
{
AsyncTest* test = new AsyncTest();
test->start();
std::this_thread::sleep_for(std::chrono::seconds(15));
return 0;
}
现在应该很清楚了,所需的功能是这样的:
Starting daemon...
Entering run() <--
Daemon started <-- These two may swap
Exiting run() <------ After 10 seconds
exit() <-- After a further 5 seconds
以下是实际发生的情况:
Starting daemon...
Entering run()
Exiting run() <-- After 10 seconds
Daemon started
exit() <-- After 15 seconds
我在带有 Debian Wheezy 的 BeagleBone Black 上运行它,它只有一个核心 - 但无论调度操作系统如何,这肯定都可以工作!
最佳答案
std::async
返回一个等待销毁的 future
,您必须为其使用成员或使用 std::thread
直接(分离)。
关于c++ - std::async 正在阻塞/暂停父线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32592054/