Hi all,
I am working with threads in C, I have written a code to create threads which execute a function. Problem is I am getting the threads created, however, the target function is not getting invoked. How do I know it? I have print statements everywhere. I get success as many times as I want the threads but none of the target function print statements are getting printed, which I feel is bizarre.
Below is my code
<<creation of threads>>
void replace(char **args)
{
char *word1=args[1];
char *word2=args[2];
int worker=atoi(args[3]);
int err;
int size=0;
size_t segment;
int i=0;
int j;
char *w_ptr;
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_replace_array[i].begin=begin;
thread_data_replace_array[i].end=end;
thread_data_replace_array[i].word1=word1;
thread_data_replace_array[i].word2=word2;
struct thread_data_replace *my_data=malloc(sizeof(struct thread_data_replace));
err=pthread_create(&(tid[i]),NULL,s_replace,(void *) &thread_data_replace_array[i]);
if (err!=0) printf("\n cant create a thread");
else printf("\n success");
}
}
<<>>
<<Target function>>
void *s_replace(void *threadarg)
{
pthread_mutex_lock(&relock);
printf("\ninside s_replace for a new thread");
struct thread_data_replace *my_data=(struct thread_data_replace *)threadarg;
int begin=my_data->begin;
int end= my_data->end;
char *word1= my_data->word1;
char *word2= my_data->word2;
int j;
int i;
printf("\ninside replace word to be replaced is %s",word1);
printf("\n inside replace replaced word is %s",word2);
printf("\n from %d to %d in replace",begin, end);
for(j=begin;j<end;j++)>
{
if(!memcmp(data+j,word1,strlen(word1)))
{
printf("inside if this time for replace function replacing words");
for(i=j;i<strlen(word1);i++)>
{
data[i]=word2[i];
}
}
}
pthread_mutex_unlock(&relock);
}
<<>>
What I have tried:
I have tried allocating the memory to the struct of arguments while creating the threads instead of in the target function. I have applied locks everywhere so I don't get erratic behavior. If it helps, m working on a unix machine with the help of an ssh.
the output I get when I give 6 threads as input is
success
success
success
success
success
success
and then the program ends