首页 > 解决方案 > 如何从 std::async 线程中启动 std::async 线程,并在第二个启动后让第一个死掉?

问题描述

我想要实现的是拥有和自主的异步线程磨,异步 A 完成它的任务,启动异步 B 并死亡。async B 重复执行相同的操作。

示例代码:main.cpp

class operation_manager : public std::enable_shared_from_this<operation_manager> {
public:
    operation_manager() {}
    void do_operation(void) {
        std::function<void(std::shared_ptr<operation_manager>)> fun( [this](std::shared_ptr<operation_manager> a_ptr) {
            if( a_ptr != nullptr ) {
                a_ptr->do_print();
            }
        } );
        i_ap.read(fun, shared_from_this());
    }

    void do_print(void) {
        std::cout << "Hello world\n" << std::flush;
        do_operation();
    }

private:
    async_operation i_ap;
};

int main(int argc, const char * argv[]) {

    auto om( std::make_shared<operation_manager>() );
    om->do_operation();
    while(true) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    return 0;
}

示例代码:async_operation.hpp

class async_operation {
public:
    async_operation() {};

    template<typename T>
    void read(std::function<void(std::shared_ptr<T>)> a_callback, std::shared_ptr<T> a_ptr) {
        auto result( std::async(std::launch::async, [&]() {
            wait();
            a_callback(a_ptr);
            return true;
        }) );
        result.get();
    }

private:
    void wait(void) const {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
};

标签: multithreadingc++11asynchronous

解决方案


您的错误是在异步任务内部调用result.get()- 这导致它阻塞并等待下一个任务完成。等待你需要做的是将期货保存在某个地方,然后让它们运行。

这是 async_operation 类的修改代码:

std::vector<std::shared_ptr<std::future<bool>>> results;

class async_operation {
public:
    async_operation() {};

    template<typename T>
    void read(std::function<void(std::shared_ptr<T>)> a_callback, std::shared_ptr<T> a_ptr) {

        results.push_back(std::make_shared<std::future<bool>>(std::async(std::launch::async, [=]() {
            wait();
            a_callback(a_ptr);
            return true;
        })));
    }

private:
    void wait(void) const {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
};

推荐阅读