【问题标题】:Getting warning of passing argument 3 of ‘pthread_create’ from incompatible pointer type [-Wincompatible-pointer-types]从不兼容的指针类型 [-Wincompatible-pointer-types] 收到有关传递“pthread_create”参数 3 的警告
【发布时间】:2021-07-25 03:32:00
【问题描述】:

我正在运行下面的代码,它工作正常,但它仍然给出了一些我不明白的警告。有人可以向我解释一下吗?谢谢

#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(&amp;thread, NULL, the_thread_func, data_for_thread); 传递“pthread_create”的参数 3 ^~~~~~~~~~~~~~~ 在 thread_data.c:2:0 包含的文件中: /usr/include/pthread.h:234:12:注意:预期 ‘void * (*)(void *)’ but argument is of type ‘void * (*)(double *)’ 外部 int pthread_create (pthread_t *__restrict __newthread,

【问题讨论】:

  • the_thread_func() 应该接受 void* 而不是 double*
  • C 还是 C++?它们是不同的语言。
  • 这是C语言

标签: c multithreading pthreads


【解决方案1】:

根据手册pthread_create 需要赋予具有此签名的函数:

void* (*start_routine)(void*)

但是你传递给它的函数是接受double*here:

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

我认为您需要更改签名并将void*inside 像这样:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 2011-01-10
    • 2020-07-29
    • 1970-01-01
    相关资源
    最近更新 更多