在不使用 Boost::p Romise 的情况下在 boost 线程中返回值

return value in boost thread without using boost::promise

本文关键字:情况下 boost 线程 返回值 Boost Romise      更新时间:2023-10-16
int xxx()
{
    return 5;
}
int main()
{
    boost::thread th;
    th = boost::thread(xxx);
    th.join();
    return 0;
}

如何在不使用 boost::p romise 的情况下捕获 xxx() 方法返回的值?

既然你说你不能改变xxx,调用另一个函数,将结果放在可访问的地方。承诺可能仍然是最好的选择,但如果你小心同步,你可以直接将其写入局部变量。例如

int result;
th = boost::thread([&]{result = xxx();});
// Careful! result will be modified by the thread.
// Don't access it without synchronisation.
th.join();
// result is now safe to access.

如注释中所述,有一个方便的async函数,它为您提供了一个从中检索异步调用函数的返回值的未来:

auto future = boost::async(boost::launch::async, xxx);
int result = future.get();

实际上我想在 main 中更改某些内容并且方法 xxx() 不可编辑

使用具有适当同步的共享对象(互斥锁、互斥锁+条件变量)

我提到的选项的采样器(显然,您不需要所有这些选项):

int global = -1;
std::mutex mtx;
std::condition_variable cv;
void xxx()
{
    // do lot of work...
    {
        std::unique_lock<std::mutex> lk(mx);
        global = 5; // safe because lock for exclusive access
        cv.notify_all();
    }
}
int main()
{
    boost::thread th(xxx);
    {
        // need to lock since the thread might be running
        // this might block until `global` is actually set
        std::unique_lock<std::mutex> lk(mx);
        cv.wait(lk, [] { return global != -1; });
        std::cout << "global has been set: " << global << "n";
    }
    th.join();
    // here there is no locking need
    return global;
}
相关文章: