簡體   English   中英

能否在C ++ 11中檢索線程函數的返回值?

[英]Can one retrieve the return value of a thread function in C++11?

如果函數具有非無效的返回值,而我使用.join函數將其加入,那么有什么方法可以檢索其返回值?

這是一個簡化的示例:

float myfunc(int k)
{
  return exp(k);
}

int main()
{
  std::thread th=std::thread(myfunc, 10);

  th.join();

  //Where is the return value?
}

您可以按照以下示例代碼從線程獲取返回值:-

int main()
{
  auto future = std::async(func_1, 2);          

  //More code later

  int number = future.get(); //Whole program waits for this

  // Do something with number

  return 0;
}

簡而言之,.get()獲取返回值,您可以鍵入並使用它。

我自己的解決方案:

#include <thread>
void function(int value, int *toreturn)
{
 *toreturn = 10;
}

int main()
{
 int value;
 std::thread th = std::thread(&function, 10, &value);
 th.join();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM