HI all,
I am trying to run a simple program in C where I map a file to a memory location and search through it using threads. I have also applied the mutex lock, so threads don't change my output. My code is compiling properly and executing properly, however now I can't seem to return an int value from the thread function.
Example of my output would be as under:
The value of count in the function is 2598 and when I return it using
printf("\n%d is the count of the word",(int)status);
it gives me something like -143003104 or 711181824
Below is my code, please tell me if I am missing anything.
#define BUFFERSIZE 64
int count=0;
char * data;
struct stat filestat;
pthread_t mid[100];
pthread_mutex_t lock;
struct thread_data{
int begin;
int end;
char *word;
};
struct thread_data thread_data_array[100];
void *s_workerSearch(void *threadarg)
{
pthread_mutex_lock(&lock);
printf("\ninside workersearch for a new thread");
struct thread_data *my_data;
my_data=(struct thread_data *) threadarg;
int begin=my_data->begin;
int end= my_data->end;
char *word= my_data->word;
printf("\nbeginning is %d\n",begin);
printf("\n end is %d",end);
printf("\n to search %s ",word);
int len=strlen(word);
printf("%d",len);
int j;
for(j=begin;j<end;j++)
{
printf("\n inside for not inside if\n");
if(!memcmp(data+j,word,strlen(word)))
{
printf("inside if for workersearch");
count++;
}
}
printf("\n count of the word inside the workersearch is %d",count);
pthread_mutex_unlock(&lock);
return (void *)count;
}
void s_search(char **args)
{
char *word=args[1];
int worker=atoi(args[2]);
printf("no of workers %d\n",worker);
int size=0;
size_t segment;
pid_t pid;
int i=0;
int j=0;
int count=0;
char *w_ptr;
int err;
int status;
for(i=0;i<worker;i++)
{
int begin = i / (float)worker * filestat.st_size;
int end = ( i + 1 )/ (float)worker * filestat.st_size;
thread_data_array[i].begin=begin;
thread_data_array[i].end=end;
thread_data_array[i].word=word;
err=pthread_create(&(mid[i]),NULL,s_workerSearch,(void *) &thread_data_array[i]);
if (err!=0) printf("\ncant create thread");
else printf("success!!!");
}
printf("\n%d is the count of the word",(int)status);
}
71,2 10%
What I have tried:
I have tried to return the value of count using the status, however, is there something wrong with my typecasting?
Also, do I join the threads and return the status, if yes, how do I go about doing that?
Also, while compiling I am getting an warning which says
warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
return (void *)count;