std :: async阻塞/暂停父线程

时间:2015-09-15 17:21:17

标签: c++ multithreading c++11 asynchronous

我正在尝试在我的应用程序中使用std::asyncstd::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运行它,它只有一个核心 - 但无论使用调度操作系统,这肯定都可以使用!

1 个答案:

答案 0 :(得分:4)

std::async返回等待销毁的future,您必须使用其成员或直接使用std::thread(已分离)。

相关问题