c ++将带有自定义对象的std :: function作为参数传递给线程

时间:2019-03-31 17:38:26

标签: c++ multithreading function

我有一个单独的类来处理线程,并且有一个函数需要创建一个线程并在特定间隔内重复该函数

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在不同的文件中并传递不同的功能

2 个答案:

答案 0 :(得分:2)

您的问题是,您要捕获lastlinedict的按值,然后将它们传递给需要非常量引用的func。您可能需要像这样捕获:

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

但是,在捕获按引用时应格外小心,以确保在lambda中使用这些对象时这些对象仍处于活动状态,尤其是考虑到您在单独的线程中调用它时。这也可能导致数据争用,因此,如果要从多个线程访问lastlinedict,则需要确保使用正确的同步机制,例如std::mutex

答案 1 :(得分:2)

按值捕获变量会使它们在lambda主体中隐式const,这就是为什么将非成本引用将其传递给func的原因。

因此,您可以按照r3mus n0x在their answer中的建议进行操作,也可以按值或以func的形式将它们传递给const ref。我想我更喜欢r3mus n0x的解决方案,因为它涉及的临时对象更少,只要所引用的变量在执行线程时不会超出范围即可。