This program counts the occurrence of a word in a line. It runs as expected, but I have 2 concerns:
- delete tmpis commented as of now (line 57). If it is uncommented and compiled, my executable gives "segmentation fault". Oddly, it doesn't crash while running in- gdbnor with- valgrind.
- Lines 65 and 66: ideally these threads would need to be joined. But, I am getting correct output even though they are not joined. Is this how it behaves for a shared (volatile) variable?
#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;
} 
 
     
    