我有一个模式匹配程序,它将字符串作为输入,并返回与字典紧密匹配的字符串。由于算法需要几秒钟才能运行一个匹配查询,因此我尝试使用多线程来运行批处理查询。
我首先读入包含查询列表的文件,并为每个查询调度一个新线程来执行匹配算法,使用pthread_join将结果返回到数组中。
然而,我得到了一些不一致的结果。例如,如果我的查询文件包含术语“红色,绿色,蓝色”,我可能会收到“红色,绿色,绿色”作为结果。另一次运行可能会生成正确的“红色,绿色,蓝色”结果。它似乎有时会在数组中写入结果,但为什么会发生这种情况,因为数组值是根据线程ID设置的?
Dictionary dict; // global, which performs the matching algorithm
void *match_worker(void *arg) {
char* temp = (char *)arg;
string strTemp(temp);
string result = dict.match(strTemp);
return (void *)(result.c_str());
}
void run(const string& queryFilename) {
// read in query file
vector<string> queries;
ifstream inquery(queryFilename.c_str());
string line;
while (getline(inquery, line)) {
queries.push_back(line);
}
inquery.close();
pthread_t threads[queries.size()];
void *results[queries.size()];
int rc;
size_t i;
for (i = 0; i < queries.size(); i++) {
rc = pthread_create(&threads[i], NULL, match_worker, (void *)(queries[i].c_str()));
if (rc) {
cout << "Failed pthread_create" << endl;
exit(1);
}
}
for (i = 0; i < queries.size(); i++) {
rc = pthread_join(threads[i], &results[i]);
if (rc) {
cout << "Failed pthread_join" << endl;
exit(1);
}
}
for (i = 0; i < queries.size(); i++) {
cout << (char *)results[i] << endl;
}
}
int main(int argc, char* argv[]) {
string queryFilename = arg[1];
dict.init();
run(queryFilename);
return 0;
}
编辑:正如Zac所建议的那样,我修改了线程以显式地将结果放在堆上:
void *match_worker(void *arg) {
char* temp = (char *)arg;
string strTemp(temp);
int numResults = 1;
cout << "perform match for " << strTemp << endl;
string result = dict.match(strTemp, numResults);
string* tmpResult = new string(result);
return (void *)((*tmpResult).c_str());
}
虽然,在这种情况下,我会在哪里进行删除调用?如果我尝试在run()函数的末尾添加以下内容,则会产生无效的指针错误。
for (i = 0; i < queries.size(); i++) {
delete (char*)results[i];
}
答案 0 :(得分:4)
如果没有调试,我的猜测是它与以下内容有关:
void *match_worker(void *arg)
{
char* temp = (char *)arg;
string strTemp(temp);
string result = dict.match(strTemp); // create an automatic
return (void *)(result.c_str()); // return the automatic ... but it gets destructed right after this!
}
因此,当下一个线程运行时,它会写入您指向的相同内存位置(偶然),并且您要插入相同的值两次(不要在其上写入)。
您应该将结果放在堆上,以确保它在您的线程退出并将其存储在主线程中之间不会被销毁。
通过编辑,你试图把事情搞得太多了。我在下面修了它:
void *match_worker(void *arg)
{
char* temp = (char *)arg;
string strTemp(temp);
int numResults = 1;
cout << "perform match for " << strTemp << endl;
string result = dict.match(strTemp, numResults);
string* tmpResult = new string(result);
return (void *)(tmpResult); // just return the pointer to the std::string object
}
将results
声明为
// this shouldn't compile
//void* results[queries.size()];
std::string** results = new std::string[queries.size()];
for (int i = 0; i < queries.size(); ++i)
{
results[i] = NULL; // initialize pointers in the array
}
清理内存时:
for (i = 0; i < queries.size(); i++)
{
delete results[i];
}
delete [] results; // delete the results array
也就是说,如果您使用C++11 threading templates而不是混合使用C pthread库和C ++,那么您将会更容易。
答案 1 :(得分:2)
问题是由局部变量result
的生命周期和成员函数result.c_str()
返回的数据引起的。通过将C与C ++混合,您可以轻松完成此任务。考虑使用C ++ 11及其线程库。它使任务变得更加容易:
std::string match_worker(const std::string& query);
void run(const std::vector<std::string>& queries)
{
std::vector<std::future<std::string>> results;
results.reserve(queries.size());
for (auto& query : queries)
results.emplace_back(
std::async(std::launch::async, match_worker, query));
for (auto& result : results)
std::cout << result.get() << '\n';
}