Tuesday, July 28, 2009

I need to know an example of writting a program in c language under linux using threads?

/*





i need to know an example of writting a program in c


language under linux using threads?





write aprogram to calculate the result of the equation


Y=3sin(x)+6cos(x)+5x2 so each term accomplished by a


thread. The main thread will calculate the result.





*/








#include %26lt;pthread.h%26gt;


#include %26lt;math.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;stdio.h%26gt;





/* static global location -- all threads will read */


static double x;





static void*


three_sinx(void*p)


{


  double* result = (double*)p;


  *result = 3 * sin(x);


  return 0;


}





static void*


six_cosx(void*p)


{


  double* result = (double*)p;


  *result = 6 * cos(x);


  return 0;


}





static void*


five_x_squared(void*p)


{


  double* result = (double*)p;


  *result = 5 * x * x;


  return 0;


}





/*


*


* Y = 3sin(x) + 6cos(x) + 5x2


*


*/





int


main(int argc, char* argv[])


{


  double result[3]; /* one location for each thread */


  pthread_t tid[3];


  void *r;


  int i;





  /* Set "x" to double value passed in on command line */


  x = argc%26gt;1 ? strtod(argv[1], 0) : 0;








  /*


   * Since result areas are distinct, no mutex needed


   */


  if (pthread_create(%26amp;tid[0], NULL,


    three_sinx, %26amp;result[0]) != 0) {


    perror("pthread_create[0]"), exit(-1);


  }





  if (pthread_create(%26amp;tid[1], NULL,


    six_cosx, %26amp;result[1]) != 0) {


    perror("pthread_create[1]"), exit(-1);


  }





  if (pthread_create(%26amp;tid[2], NULL,


    five_x_squared, %26amp;result[2]) != 0) {


    perror("pthread_create[2]"), exit(-1);


  }





  /* Synchronize on the completing child threads */


  for (i=0; i%26lt;3; i++) {


    if (pthread_join(tid[i], %26amp;r) != 0) {


      perror("pthread_join");


      exit(-1);


    }


  }





  /* main thread will now combine the result */


  printf("For y=3sin(x)+6cos(x)+5x2, when x=%f, y=%f\n",


      x, result[0]+result[1]+result[2]);





  return 0;


}











To show that it works:





$ cc pthr.c -lpthread -lm





$ a.out 3.14159


For y=3sin(x)+6cos(x)+5x2, when x=3.141590, y=43.347947





$ a.out 0


For y=3sin(x)+6cos(x)+5x2, when x=0.000000, y=6.000000

I need to know an example of writting a program in c language under linux using threads?
for linux, you need to use POSIX threads. you can read more about it here:


No comments:

Post a Comment