簡體   English   中英

在新線程中調用方法,並將返回值分配給變量

[英]Call method in new thread and assign returned value to variable

我試圖將方法稱為新線程,並將方法返回的值分配給變量。

例如:

int numObjects = thread t7(methodName(parameter));

我該怎么做呢?

我確定我缺少一些簡單的東西,但這讓我很困惑。

提前致謝

您需要將std::futurestd::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.

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