Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;在线程中以自定义对象作为参数传递std::函数_C++_Multithreading_Function - Fatal编程技术网

C++ c++;在线程中以自定义对象作为参数传递std::函数

C++ c++;在线程中以自定义对象作为参数传递std::函数,c++,multithreading,function,C++,Multithreading,Function,我有一个单独的类来处理线程,有一个函数需要创建一个线程并在特定的时间间隔内重复该函数 void timer_start_custom(std::function<void(string, string&, vector<CustomObject>&)> func, string filename, string& lastline, vector<CustomObject>& dict, unsigned int interva

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

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();
}
void timer\u start\u custom(std::function func、字符串文件名、字符串和lastline、向量和dict、无符号整数间隔){
线程([func,interval,filename,lastline,dict](){
while(true){
自动x=std::chrono::Standy_clock::now()+std::chrono::毫秒(间隔);
func(文件名、最后一行、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> &)>')
对“const”类型对象的调用没有匹配函数
std::函数(aka)
‘常量函数’)

我知道如果将函数放在同一个文件中,那么我可以跳过func作为参数,但我仍然非常好奇和固执地想知道如何解决这个问题,正如我将在不同的文件中调用
计时器\u start\u custom
并传入不同的函数一样

您的问题是,您正在按值捕获
最后一行
dict
,然后将它们传递给
函数
,该函数需要非常量引用。您可能需要像这样捕捉:

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

但是,当通过引用捕获时,您应该特别小心,以确保这些对象在lambda中使用时仍然是活动的,特别是考虑到您在单独的线程中调用它。这也造成了数据竞争的可能性,因此如果要从多个线程访问
lastline
dict
,则需要确保使用适当的同步机制,如
std::mutex

通过值捕获变量会使它们隐式地
const
在lambda的主体中,这就是为什么将它们作为非成本引用传递给
func
无法编译的原因


因此,您可以按照r3mus n0x中的建议执行操作,也可以通过值或作为
const ref
将它们传递给
func
。我想我更喜欢r3mus n0x的解决方案,因为它涉及较少的临时变量,前提是线程执行时引用的变量不超出范围。

缩进代码。-通过非常量引用传递
lastline
dict
的原因是什么?以何种方式传递较少的临时变量?@lightness racesinorbit,例如,制作dict的副本可能很昂贵。谢谢您的编辑。哦,是的,通过值传递是不好的。@LightnessRacesinOrbit是的。我发布了一个答案,主要是为了解释为什么原始代码不能编译。@PaulSanders对无意义的编辑表示抱歉-我以为我在编辑我自己的答案。该睡觉了。