【发布时间】:2017-10-17 13:46:25
【问题描述】:
我有 8 个数据集作为对存储在一个向量中,并决定一个一个地传递到一个类中,并使用该类中的一个函数做一些工作。产生分段错误。这是我的代码:
vector<thread> threads;
for (int i = 0; i < 8; i++) { // generate 8 threads
LogOdd CEB; // create LogOdd obj
CEB.set_data(coord[i].second, coord[i].first); // pass parameters to private members
threads.push_back(thread(&LogOdd::scan, &CEB));
for (int i = 0; i < 8; i++){
threads[i].join();
}
类看起来像:
class LogOdd {
private:
string sequence;
string chromosome;
public:
void scan() { // function to be threaded
...
}
void set_data(string SEQUENCE, string CHROMOSOME) { // set parameters
sequence = SEQUENCE;
chromosome = CHROMOSOME;
}
};
我很确定在第一个线程 for 循环中生成的分段错误,但不知道......我知道这个主题可能是重复的,但我已经做了很多搜索。请帮忙!
更新 谢谢回答我的问题。我以 2 种方式编辑了我的代码,它们都可以工作!
vector<thread> threads;
for (int i = 0; i < 8; i++) { // generate 8 threads
LogOdd * CEB = new LogOdd; // create LogOdd obj
CEB->sequence = coord[i].second;
CEB->chromosome = coord[i].first;
threads.push_back(thread(&LogOdd::scan, CEB));
}
我做的另一种方法是先将所有 8 个 obj 存储到一个向量中,然后分配给线程:
vector<thread> threads;
vector<LogOdd> LogOddvec;
for (int i = 0; i < 8; i++) {
LogOdd CEB;
CEB.sequence = coord[i].second;
CEB.chromosome = coord[i].first;
LogOddvec.push_back(CEB);
}
for (int i = 0; i < 8; i++) {
threads.push_back(thread(&LogOdd::scandinuc, &LogOddvec[i]));
}
【问题讨论】:
-
想想这个对象的生命周期是多少:
LogOdd CEB;
标签: c++ multithreading class segmentation-fault