【问题标题】:return value in boost thread without using boost::promise在不使用 boost::promise 的情况下在 boost 线程中返回值
【发布时间】:2015-01-07 13:44:34
【问题描述】:
int xxx()
{
    return 5;
}

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

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

【问题讨论】:

  • 你为什么不想使用promise?唯一的选择是写一些做同样事情的东西,这似乎毫无意义。
  • 其实我想在 main 中改变一些东西,方法 xxx() 是不可编辑的
  • @Bakkya boost::future?
  • @UldisK boost::future 只有在我们使用 boost::promise 时才能使用。但我不想使用 boost::promise
  • @UldisK 我得到了正确的解决方案!请参考以下答案

标签: c++ boost boost-thread


【解决方案1】:

既然您说您不能更改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.

正如 cmets 中提到的,有一个方便的 async 函数,它为您提供了一个将来检索异步调用函数的返回值的方法:

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

【讨论】:

  • OP 可以调用 do int result = xxx(); 来产生这种效果。 (如果 main 中没有显示更多的工作,想必他可以把那个工作放在一个线程上)
  • @sehe:你可以和xxx同时做其他事情,这大概就是线程存在的原因。
  • 如图所示,连接反驳了并发性。不过,请查看对我的评论的编辑
  • @sehe:你可以在join之前做些别的事情,同时执行xxx,这大概就是线程存在的原因。然后在需要结果时join
  • 谢谢!!!这是一个好方法!如果类示例中存在 xxx(),我该如何使用此方法?
【解决方案2】:

实际上我想在 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;
}

【讨论】:

  • 或者您可以在需要结果时简单地加入线程;这将提供与这种过于复杂的舞蹈相同的同步。
  • @MikeSeymour 如果您仔细观察,您会发现我实际上也在示例中准确地展示了这一点(提示return global)。此外,答案在第一行。代码只是对我提到的抽象进行抽样
  • 好的。对我来说,答案似乎意味着您需要复杂的舞蹈,而不仅仅是简单的join,来检索结果。也许我读得太多了。
  • 使用锁是个好主意。但正如我之前提到的,我不想改变 xxx() mwthod
  • 但是通过使用这种方式我们想对 xxx() 方法添加一些更改
猜你喜欢
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多