簡體   English   中英

將lambdas傳遞給std :: thread並調用類方法

[英]Passing lambdas to std::thread and calling class methods

我在使用std :: thread和lambdas時遇到了一些麻煩。 我有一個方法TheMethod我應該使用std :: thread來並行化對同一個類中的方法的一些函數調用。

我定義了一個lambda函數,並嘗試將它傳遞給我創建的std :: thread實例:

auto functor = 
   [this](const Cursor& c, size_t& result) ->void {result = classMethod(c);};

size_t a;
Cursor cursor = someCursor();

std::thread t1(functor, cursor, a);

t1.join();

不幸的是,編譯器給了我:

  /usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<TheMethod...

我在lambda定義中嘗試了很多組合,並且調用了std :: thread構造函數,但是我總是得到相同的錯誤。 包含了線程庫,我也鏈接了pthread。

謝謝你的提示!

您可以使用std :: ref通過引用傳遞參數:

std::thread t1(functor, std::ref(cursor), std::ref(a))

您還可以通過lambda本身中的引用捕獲參數:

size_t a;
Cursor cursor = someCursor();
std::thread t1([&] {a = classMethod(cursor);});
t1.join();

這是因為對象游標和a通過值傳遞給線程的構造函數。 仿函數引用了新創建的線程的本地副本,而不是您期望它們的對象。

因此,正如“alexk7”所回答的那樣,你應該使用std :: ref,或者如果你想通過引用捕獲它們

暫無
暫無

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

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