![](/img/trans.png)
[英]what is the return type of the new operator in c++ & why can we assign the returned value to a variable(non-pointer)?
[英]Call method in new thread and assign returned value to variable
我試圖將方法稱為新線程,並將方法返回的值分配給變量。
例如:
int numObjects = thread t7(methodName(parameter));
我該怎么做呢?
我確定我缺少一些簡單的東西,但這讓我很困惑。
提前致謝
您需要將std::future
與std::async
結合使用。
std::future<int> fut = std::async(methondname, parameter);
// do something
// will wait for the result to become available
std::cout << fut.get() << std::endl;
我還建議閱讀鏈接到的std::async
文檔,因為它們有不同的啟動策略,例如:它確實在單獨的線程中運行還是偷懶地執行。
另一種可能性是僅將輸出參數(通過std::ref
)與std::thread
,然后您將必須手動加入並且也不會獲得繼承給std::async
的異常安全性。 因此,您最好堅持使用std::async
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.