簡體   English   中英

C ++在線程中傳遞帶有自定義對象的std :: function作為參數

[英]c++ passing std::function with custom object as argument in threading

我有一個單獨的類來處理線程,並且有一個函數需要創建一個線程並在特定間隔內重復該函數

void timer_start_custom(std::function<void(string, string&, vector<CustomObject>&)> func, string filename, string& lastline, vector<CustomObject>& dict, unsigned int interval){
     std::thread([func, interval, filename, lastline, dict](){
         while (true){
             auto x = std::chrono::steady_clock::now() + std::chrono::milliseconds(interval);
             func(filename, lastline, dict);
             std::this_thread::sleep_until(x);
         }
     }).detach();
}

但是,現在編譯器compain:

No matching function for call to object of type 'const
std::function<void (string, string &, vector<RowData> &)>' (aka
'const function<void (basic_string<char, char_traits<char>, allocator<char> >,
basic_string<char, char_traits<char>, allocator<char> > &, vector<RowData> &)>')

我知道如果將函數放在同一文件中,那么我可以跳過func作為參數,但是我仍然非常好奇和固執,不知道如何解決此問題,因為我將在其他文件中調用timer_start_custom並傳遞不同的參數職能

你的問題是,你正在拍攝lastlinedict的值,然后將它們傳遞給func其中預計非const引用。 您可能需要像這樣捕獲:

std::thread([func, interval, filename, &lastline, &dict] {
...
});

但是,在捕獲按引用時應格外小心,以確保在lambda中使用這些對象時這些對象仍處於活動狀態,尤其是考慮到要在單獨的線程中調用它的情況下。 這也可能導致數據爭用,因此,如果您要從多個線程訪問lastlinedict ,則需要確保使用適當的同步機制,例如std::mutex

通過值捕獲變量使它們在lambda主體中隱式為const ,這就是為什么將它們作為非成本引用傳遞給func無法編譯的原因。

因此,您可以執行r3mus n0x在其答案中建議的操作 ,也可以按值或將其作為const ref傳遞給func 我認為我更喜歡r3mus n0x的解決方案,因為它涉及的臨時項較少,只要所引用的變量在執行線程時不會超出范圍。

暫無
暫無

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

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