1
votes

I am running the below code and it is working fine but still it is giving some warning which i don't understand. Can someone please explain this to me ? Thanks

#include <stdio.h>
#include <pthread.h>

void* the_thread_func(double data_for_thread[]) {
  /* Do something here? */

        for(int i=0;i<3;i++){
    double sum = sum + data_for_thread[i];
    printf("The sum done by the_thread_func()  is = %f\n",sum);
   }

  return NULL;
}

int main() {
  printf("This is the main() function starting.\n");

  double data_for_thread[3];
  data_for_thread[0] = 5.7;
  data_for_thread[1] = 9.2;
  data_for_thread[2] = 1.6;

  /* Start thread. */
  pthread_t thread;
  printf("the main() function now calling pthread_create().\n");
  pthread_create(&thread, NULL, the_thread_func, data_for_thread);

  printf("This is the main() function after pthread_create()\n");

  /* Do something here? */

   for(int i=0;i<3;i++){
   double sum = sum + data_for_thread[i];
    printf("The sum done by main() is = %f\n",sum);
   }

  /* Wait for thread to finish. */
  printf("the main() function now calling pthread_join().\n");
  pthread_join(thread, NULL);

  return 0;
}

warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [-Wincompatible-pointer-types] pthread_create(&thread, NULL, the_thread_func, data_for_thread); ^~~~~~~~~~~~~~~ In file included from thread_data.c:2:0: /usr/include/pthread.h:234:12: note: expected ‘void * (*)(void *)’ but argument is of type ‘void * (*)(double *)’ extern int pthread_create (pthread_t *__restrict __newthread,

1
the_thread_func() should accept a void* not a double*.Galik
C or C++? They are different languages.Andrew Henle
this is C languageSalman Khan

1 Answers

1
votes

According to the manual pthread_create needs to be given a function with this signature:

void* (*start_routine)(void*)

But you are passing it a function that accepts double*here:

void* the_thread_func(double data_for_thread[]) // decays to double*

I think you need to change the signature and cast the void*inside the function like this:

// accept void*
void* the_thread_func(void* vp) {
  /* Do something here? */

    double* data_for_thread = reinterpret_cast<double*>(vp); // cast here

    for(int i=0;i<3;i++){
        double sum = sum + data_for_thread[i];
        printf("The sum done by the_thread_func()  is = %f\n",sum);
    }

    return nullptr;
}