簡體   English   中英

從不兼容的指針類型 [-Wincompatible-pointer-types] 獲取傳遞“pthread_create”參數 3 的警告

[英]Getting warning of passing argument 3 of ‘pthread_create’ from incompatible pointer type [-Wincompatible-pointer-types]

我正在運行下面的代碼,它工作正常,但它仍然給出了一些我不明白的警告。 有人可以向我解釋一下嗎? 謝謝

#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;
}

警告:從不兼容的指針類型 [-Wincompatible-pointer-types] pthread_create(&thread, NULL, the_thread_func, data_for_thread); ^~~~~~~~~~~~~~~ 在thread_data.c:2:0: /usr/include/pthread.h:234:12: 注意:預期'void * (*)(void *)' but argument is of type 'void * (*)(double *)' extern int pthread_create (pthread_t *__restrict __newthread,

根據手冊pthread_create需要給出一個具有此簽名的 function:

void* (*start_routine)(void*)

但是您傳遞給它的 function 在這里接受double*

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

我認為您需要更改簽名並將void*投射到 function 中,如下所示:

// 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM