簡體   English   中英

如何將此std :: function傳遞給std :: async

[英]How can I pass this std::function to std::async

我正在處理一段多線程代碼,但似乎無法將std :: function對象傳遞給std :: async函數。 我確定我做錯了什么,但我不知道那會是什么。 因此,我准備了這段代碼,以便也許有人認識可以幫助我。

Test1演示此std :: function對象起作用。
Test2包含我想要執行的操作; 只有我將函數對象包裝到lambda中。
Test3包含我不知道的示例。

std::function<void(AsyncFunctionExample&)> current_function;

void Test1() {
  current_function = &AsyncFunctionExample::Function1;
  while(current_function != nullptr)
    current_function(*this);
}

void Test2() {
  current_function = &AsyncFunctionExample::Function1;
  while(current_function != nullptr)
    const std::future<void> function_future = std::async([&](){current_function(*this);});
}

void Test3() {
  current_function = &AsyncFunctionExample::Function1;
  while(current_function != nullptr)
    const std::future<void> function_future = std::async(current_function, *this);
}

此示例的完整代碼可以在此處找到。 Stackoverflow編輯器警告說,不允許我轉儲完整的代碼文件,所以這就是為什么在這里將其簡化為基本內容的原因。

我收到的編譯器錯誤是:
沒有匹配的函數可以調用'async(std :: function&,AsyncFunctionExample&)'const std :: future function_future = std :: async(current_function,* this);

這對我沒有多大幫助。 它基本上向我說明,沒有與我的呼叫匹配的簽名。 但是我無法從該錯誤中找出呼叫的哪一部分是錯誤的,並且我不知道如何更改它才能正常工作。

您不能通過std::async傳遞引用,因為它需要復制值。 您可以使用std::ref修復此問題:

const std::future<void> function_future = std::async(current_function, std::ref(*this));

或者,只需將功能更改為:

std::function<void(AsyncFunctionExample*)> current_function;

然后,您可以直接傳遞this

const std::future<void> function_future = std::async(current_function, this);

暫無
暫無

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

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