return 不使用 boost::promise 的提升线程中的值

return value in boost thread without using boost::promise

int xxx()
{
    return 5;
}

int main()
{
    boost::thread th;
    th = boost::thread(xxx);
    th.join();
    return 0;
}

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

Actually i want to change something in main & the method xxx() is not editable

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

我提到的选项的示例(显然你不需要所有选项):

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;
}

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

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 函数,它为您提供了一个未来,可以从中检索异步调用函数的 return 值:

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