簡體   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