繁体   English   中英

从线程执行的函数返回结构数组

[英]return an array of structs from a function executed by a thread

我有一个从函数返回的2个字符串的结构数组。 但是此函数被称为线程的可调用函数的一部分

struct mystruct* myfunc(char* param1, int param2, int param3);

std::thread t1(myfunc, param1, param2, param3);

我从std :: thread文档中了解到,myfunc的返回值将被忽略。 但是我需要这些数据。 有没有办法获取这些数据? 我读到有一些类似std :: promise和std :: future的东西,但是真的不明白它们是什么。 有人可以帮我举一个简单的例子来实现这一目标吗?

非常感谢,提前。

埃萨什

如您所说,执行此操作的正确方法可能是使用std::futurestd::async 正如cppreferece所说:

类模板std :: future提供了一种机制来访问异步操作的结果

这就是std::async进入的地方。函数myfunc将使用std::async启动,它将返回一个“ future”值(稍后我们将进行介绍)。 一旦启动了异步函数,您只需要询问std::future变量就可以在准备就绪时获取该返回值。 您的代码如下所示:

// This will call myfunc asynchronously and assign its future return value to my_fut
std::future<mystruct*> my_fut = std::async(myfunc, param1, param2, param3);

/* 
   Do some work
*/

// We are ready to assign the return value to a variable, so we ask
// my_fut to get that "future" value we were promised.
mystruct* mptr = my_fut.get();

我认为这就是您所需要的。

正如@Fransisco Callego Salido所说的那样,执行所需操作的唯一方法是使用std :: async,但要小心std :: async不保证您的函数将异步运行。 正如cppreference所说。

模板函数async异步运行函数f(可能在单独的线程中,该线程可能是线程池的一部分),并返回std :: future,该变量最终将保存该函数调用的结果。

为了异步运行myfunc,您必须将另一个参数传递给策略std :: async的构造函数。 目前有3条政策

  • std :: launch :: async-保证您的功能将在新线程上运行。
  • std :: launch :: deferred-当您决定调用返回的future的成员函数时,将在当前线程上调用您的函数。
  • std :: launch :: async | std :: launch :: deferred-由实现决定是否在新线程上运行函数。

要记住的另一件事是,如果忘记将std :: launch :: async |传递给std :: async的构造函数,则该策略总是作为第一个参数传递给它。 std :: launch:将使用延迟策略! 因此,为了确保您的函数在新线程上执行,您必须像这样调用它。

std::future<mystruct*> myfunc_future=std::async(std::launch::async, myfunc, param1, param2, param3);
mystruct* myfunc_result=myfunc.get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM