不使用boost :: promise在boost线程中返回值

时间:2015-01-07 13:44:35

标签: c++ boost boost-thread

int xxx()
{
    return 5;
}

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

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

2 个答案:

答案 0 :(得分:0)

  

实际上我想改变一下主要内容和内容。方法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;
}

答案 1 :(得分:0)

由于您说您无法更改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();