这个程序计算一个单词在一行中的出现次数。它像预期的那样运行,但是我有两个问题:
-
delete tmp
现在被注释了(第57行)。如果它是未注释和编译的,我的可执行文件给出"分段错误"。奇怪的是,它不会崩溃,而运行在gdb
或valgrind
。 - 第65行和第66行:理想情况下,这些线程需要连接。但是,即使它们没有连接,我也能得到正确的输出。这是一个共享(volatile)变量的行为吗?
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <fstream>
#include <new>
#define MAX_BUFF 1000
using namespace std;
volatile int tcount=0;
pthread_mutex_t myMux;
typedef struct data
{
string line;
string arg;
}tdata;
void *calcWordCount(void *arg)
{
tdata *tmp = (tdata *)arg;
string line = tmp->line;
string s = tmp->arg;
int startpos = 0;
int finds = 0;
while ((startpos = line.find(s, startpos)) != std::string::npos)
{
++finds;
startpos+=1;
pthread_mutex_lock(&myMux);
tcount++;
pthread_mutex_unlock(&myMux);
}
//cout<<endl<<line<<s<<" "<<finds<<endl;
}
int main(int argc,char *argv[])
{
pthread_t thread_ids[10000];
int cnt=1;
int thread_cnt=0;
void *exit_status;
int targc=argc;
ifstream infile("testfile");
string line;
while(getline(infile,line))
{
while(targc >1)
{
tdata *tmp = new tdata;
tmp->line = line;
tmp->arg = argv[cnt];
pthread_create(&thread_ids[thread_cnt],NULL,calcWordCount,tmp);
thread_cnt++;
cnt++;
targc--;
//delete tmp;
}
cnt=1;
targc=argc;
}
infile.close();
int j;
/*for(j=0;j<thread_cnt;j++)
pthread_join(thread_ids[j],&exit_status);*/
cout<<tcount<<endl;
return 0;
}
当你在tmp
上调用delete
而另一个线程正在消耗它时,你有未定义的行为。
一个修复将创建和传递(按值)一个std::shared_ptr
而不是裸指针到你的工作线程。您可以在主循环中使用release
和reset
方法。一旦工作线程完成,内存将被std::shared_ptr
释放。