We help IT Professionals succeed at work.

Bus error with pthread

ALNMOO
ALNMOO asked
on
Medium Priority
971 Views
Last Modified: 2011-09-20
Hi,

This program takes files name as arguments and count lines on each by thread.

in execution times it gave me "Bus error"


#include <stdio.h>
#include <string.h>
#include <sys/wait.h>

FILE *in;  
int count;
int sum1=0,i;
char Buffer[256];

CountLines (char *file){
      
      strcpy(input, file);
      in = fopen(input, "r");

      if (in == NULL)
                  {
      printf("Error In Files opening\n");
      exit(-1);
                  }

      count = 0;
      while (1)
            {
            fgets (Buffer, 256, in);
            if (feof (in))
            break;
            ++count;
      }
      /*sum1=sum1+count;*/
      sum1=sum1+count;
      
}
int main (int argc, char *args[])  
{
      pthread_t tid1;
      
      for (i=1;i<argc ;i++)
      pthread_create(&tid1,NULL,CountLines (args[i]), NULL);
      pthread_join(tid1,NULL);
      
      /*count=CountLines (args[1]);*/
            printf("%d",sum1);
      fclose(in);
      
      
      exit(0);
}
Comment
Watch Question


Well, first of all, your pthread_create is incorrect.
You rather want to pass args[i] as the arg (the
last) parameter.

Second, the signature of the thread function is
incorrect. A thread function should return a
void*.

Third, your string "input" is not defined.

Thomas
Add on:

You don't want to exit if the file doesn't exist,
better use    return 0;  

You have to synchronize access to the global
variables.

You have to close the input file in your thread
routine (where you'Ve opened it).

You have to join all the threads, not just the
last one ;-)

Thomas