如何从称为函数的函数中获取返回值,该函数在TBB的另一个线程中执行? [英] How to get return value from a function called which executes in another thread in TBB?

查看:90
本文介绍了如何从称为函数的函数中获取返回值,该函数在TBB的另一个线程中执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码中:

    #include <tbb/tbb.h>

    int GetSomething()
    {
        int something;
        // do something
        return something;
    }

    // ...
    tbb::tbb_thread(GetSomething, NULL);
    // ...

此处GetSomething()通过另一个指针在另一个线程中被调用.但是我们可以从GetSomething()获取返回值吗?怎么样?

Here GetSomething() was called in another thread via its pointer. But can we get return value from GetSomething()? How?

推荐答案

如果将C ++ 03和tbb绑定在一起,则必须使用Outputarguments,这意味着必须重写函数.

If you are bound C++03 and tbb you have to use Outputarguments, which means that you have to rewrite your function.

例如:

void GetSomething(int* out_ptr);

int var = 23;

tbb::tbb:thread(GetSomething, &var); // pay attention that this doesn't run of scope

或通过boost::ref您可以执行以下操作:

or with boost::ref you can do this:

void GetSomething(int& out);

int var = 23;
tbb::tbb_thread(GetSomething, boost::ref(var)); // pay attention here, too

如果可以使用C ++ 11,则可以使用futures简化任务:

If you can use C++11 the task is simplified by using futures:

例如:

std::future<int> fut = std::async(std::launch::async, GetSomething);

....

// later

int result = fut.get();

这里您不必重写任何内容.

Here you don't have to rewrite anything.

这篇关于如何从称为函数的函数中获取返回值,该函数在TBB的另一个线程中执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆