Jim

threads prog2

No preview for this file type
  1 +#include <stdio.h>
  2 +#include <pthread.h>
  3 +
  4 +#define STEP 4000000
  5 +
  6 +void* fibonacci_work(void* sum_ptr){
  7 +
  8 + long int sum;
  9 + int one, two, three;
  10 +
  11 + one=1;
  12 + two=2;
  13 + three = 0;
  14 + sum = 0;
  15 + while (two <= STEP){
  16 +
  17 + three = one + two;
  18 +// printf ("%i,", three);
  19 +
  20 + if ( (two % 2 ) == 0)
  21 + sum += two;
  22 +// printf ("sum is now: %lu\n", sum);
  23 + one = two;
  24 + two = three;
  25 +
  26 +
  27 +
  28 + }
  29 +
  30 + pthread_exit((void*) sum);
  31 +}
  32 +
  33 +
  34 +
  35 +int main () {
  36 +
  37 + pthread_t thread1;
  38 + pthread_attr_t attr;
  39 + long sum;
  40 +
  41 + pthread_attr_init(&attr);
  42 + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  43 +
  44 + if (pthread_create (&thread1, &attr, fibonacci_work, NULL)){
  45 + fprintf (stderr, "Error creating thread\n");
  46 + return 1;
  47 + }
  48 +
  49 + pthread_attr_destroy(&attr);
  50 +
  51 + if (pthread_join (thread1,(void **)&sum)){
  52 + fprintf(stderr, "Error joining thread\n");
  53 + return 2;
  54 + }
  55 +
  56 +
  57 + printf("sum: %lu\n", sum);
  58 +
  59 + return 0;
  60 +}