首页 文章

获得未来的结果而不会阻止

提问于
浏览
0

之前已经问过这个问题,如果我没有错,读取未来结果的唯一方法是调用get()并阻塞直到它准备就绪或使用wait_for(),持续时间为零 - 如答案中所述 - Get the status of a std::future

但是,如果我只是想让一个工作线程返回给我一个我希望它计算的结果而不是等待或阻止自己完成它,我是否可以不传递一个工作线程在计算出来时可以调用的回调结果对我?像下面的东西 -

#include <iostream>
#include <thread>
#include <functional>

void foo(std::function<void(int)> callback)
{
    int result = 5;
    callback(result);
}

int main()
{
    int result = 0;
    std::thread worker(foo, [](int result) 
    {
        std::cout << "Result from worker is " << result << std::endl;
    });
    worker.join();
}

这里,工作线程只会在为我计算结果时执行回调 . 我不必等待它完成或阻止或检查循环以了解它何时准备好 . 请注意这是一个很好的方法,因为目前没有办法在没有阻塞或循环检查的情况下这样做吗?

1 回答

  • 1

    您当然可以使用回调创建自己的线程,但只要您离开玩具示例,您就会注意到您可能已经创建了同步问题 . 这是因为您的回调是从一个单独的线程调用的 . 因此,您可能希望让工作线程将消息发布到稍后将读取的队列,除非没有共享状态或已经存在互斥锁 .

    在您的具体示例中,我们添加一行代码:

    int main()
    {
        std::thread worker(foo, [](int result) 
        {
            std::cout << "Result from worker is " << result << std::endl;
        });
        std::cout << "I am the main thread" << std::endl; // added
        worker.join();
    }
    

    您可能认为只有两种可能的输出:

    I am the main thread
    Result from worker is 5
    

    Result from worker is 5
    I am the main thread
    

    但实际上还有其他可能的输出,例如:

    Result from worker is I am the main thread
    5
    

    所以你创造了一个bug . 您需要在共享状态(包括I / O)上进行同步,或者您需要协调主线程中的所有内容(阻塞或检查未来结果会给您带来什么) .

相关问题