[英]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
並傳遞不同的參數職能
你的問題是,你正在拍攝lastline
和dict
的值,然后將它們傳遞給func
其中預計非const引用。 您可能需要像這樣捕獲:
std::thread([func, interval, filename, &lastline, &dict] {
...
});
但是,在捕獲按引用時應格外小心,以確保在lambda中使用這些對象時這些對象仍處於活動狀態,尤其是考慮到要在單獨的線程中調用它的情況下。 這也可能導致數據爭用,因此,如果您要從多個線程訪問lastline
和dict
,則需要確保使用適當的同步機制,例如std::mutex
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.