将参数传递给pthread_create()函数时出错 - Visual C ++

时间:2011-11-16 15:45:22

标签: visual-c++ pthreads

以下代码返回错误:

  

错误C2664:'pthread_create':无法从'void转换参数3   *(__ cdecl *)(void)'to'void *(__ cdecl *)(void *)'

     

错误C2664:'pthread_create':无法从'void转换参数3   *(__ cdecl *)(void)'to'void *(__ cdecl *)(void *)'

代码:

#include <windows.h> 
#include <stdio.h>
#include <pthread.h> 
int main()  {
  pthread_t f2_thread, f1_thread; 
  void *f2(), *f1();
  int i1,i2;
  i1 = 1;
  i2 = 2;
  pthread_create(&f1_thread,NULL,f1,&i1);
  pthread_create(&f2_thread,NULL,f2,&i2);
  pthread_join(f1_thread,NULL);
  pthread_join(f2_thread,NULL);

  return 0;

}
void *f1(int *x){
  int i;
  i = *x;
 Sleep(1);
  printf("f1: %d",i);
  pthread_exit(0); 
}
void *f2(int *x){
  int i;
  i = *x;
 Sleep(1);
  printf("f2: %d",i);
  pthread_exit(0); 
}

环境:

2 个答案:

答案 0 :(得分:0)

不确定这是否能回答您的问题(或您的问题是什么),但这里有一些代码可以编译并提供您对输出的期望:

    #include <windows.h> 
    #include <stdio.h>
    #include <pthread.h> 
    int main()  {
      pthread_t f2_thread, f1_thread; 
      void *f2(void*), *f1(void*);
      int i1,i2;
      i1 = 1;
      i2 = 2;
      pthread_create(&f1_thread,NULL,f1,&i1);
      pthread_create(&f2_thread,NULL,f2,&i2);
      pthread_join(f1_thread,NULL);
      pthread_join(f2_thread,NULL);

      return 0;

    }
    void *f1(void *x){
  int* data = static_cast<int*>(x);
      int i = *data;
      Sleep(1);
      printf("f1: %d",i);
      pthread_exit(0); 
      return 0;
    }
    void *f2(void *x){
      int* data = static_cast<int*>(x);
      int i = *data;
      Sleep(1);
      printf("f2: %d",i);
      pthread_exit(0); 
      return 0;
    }

所以

  1. 在原型中有void *参数然后将它们转换为int *
  2. 让每个函数返回0

答案 1 :(得分:0)

请添加&#34;返回NULL:&#34;退出线程函数之前。