【发布时间】:2017-10-29 19:27:48
【问题描述】:
如何用线程调用类方法?
我的班级:
using namespace std;
class series{
private:
string filename;
vector<double> data;
public:
series(string _filename);
int loaddata(const int col);
void readdata() const;
};
series::series(string _filename):filename(_filename) {}
int series::loaddata(const int col)
{
ifstream input(filename);
string line;
if (!input) {
cout << "File failed to open" << endl;
return 0;
}
while(!input.eof())
{
while(getline(input, line)){
vector<string> oneline;
boost::split(oneline, line, boost::is_any_of("|"));
data.push_back(boost::lexical_cast<double>(oneline[col]));
}
}
return 1;
}
从 main 调用它,只发布相关部分。 csv 是文件名向量,基本上是字符串向量。
vector<series> ts;
int col = 0;
vector<thread> th;
for (unsigned int i = 0; i != csv.size(); ++i) {
ts.push_back(series(csv[i]));
th.emplace_back(thread(&series::loaddata, ref(ts[i]), col));
}
给出我无法理解的错误。
/usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple<std::_Mem_fn<int (series::*)(int)>(std::reference_wrapper<series>, int)>’:
/usr/include/c++/4.8/thread:137:47: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = int (series::*)(int); _Args = {std::reference_wrapper<series>, int}]’
/home/d066537/ClionProjects/correlation/src/main.cpp:105:66: required from here
/usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<int (series::*)(int)>(std::reference_wrapper<series>, int)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/include/c++/4.8/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<int (series::*)(int)>(std::reference_wrapper<series>, int)>’
_M_invoke(_Index_tuple<_Indices...>)
请解决,对程序使用 Clion CMake,是的,线程适用于免费功能,所以我认为这与任何编译器标志无关。
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -lpthread -std=c++11")
如果我从对象中删除 ref 包装器,我会收到此错误:
terminate called after throwing an instance of 'std::system_error' what(): Enable multithreading to use std::thread: Operation not permitted
现在更新到 g++-5,没有 ref 包装器,再次出现错误: CMakeFiles/correlation.dir/src/main.cpp.o:在函数中
`std::thread::thread<int (series::*)(int), series&, int>(int (series::*&&)(int), series&, int&&)':
/usr/include/c++/5/thread:137: undefined reference to `pthread_create'
【问题讨论】:
-
您不需要为要用于线程函数的对象使用
ref包装器。 -
另请注意,GCC 4.8 版现在已经很老了,它没有完整的 C++11 功能。尝试更新到更高版本的 GCC,然后重试。
-
如果我删除 ref wrapper 我得到这个错误:在抛出一个 'std::system_error' 实例后调用终止 what(): Enable multithreading to use std::thread: Operation not allowed
-
最后(但与您的问题无关,这很可能是由于您的 GCC 的旧且未完全 c++11 状态),请花点时间阅读Why is iostream::eof inside a loop condition considered wrong?。
-
查找there
标签: c++ multithreading class-method