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

std::async is blocking/pausing the parent thread

本文关键字:线程 暂停 阻塞 async Std      更新时间:2023-10-16

我试图在我的应用程序中使用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 startedn");
    }
};
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

我在BeagleBone Black和Debian Wheezy上运行这个,它只有一个核心-但肯定这应该工作,不管调度操作系统!

std::async返回一个等待销毁的future,你必须为它使用一个成员或直接使用std::thread(分离)