当显然没有错误时,为什么编译器在这里抱怨?

Met*_*est 1 c c++ linux gcc g++

每当我尝试编译以下程序时,我都会从编译器(g ++ 4.4.3)获得此消息.有什么想法,为什么?

main.cpp: In function ‘int main(int, char**)’:
main.cpp:52: error: void value not ignored as it ought to be
Run Code Online (Sandbox Code Playgroud)

第52行的代码为rc = pthread_create_with_stack(&thread [t],BusyWork,t);

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define NUM_THREADS 4

void *stackAddr[NUM_THREADS];
pthread_t thread[NUM_THREADS];
pthread_attr_t attr;

void *BusyWork(void *t)
{
   int i;
   long tid;
   double result=0.0;
       tid = (long)t;
   printf("Thread %ld starting...\n",tid);
   for ( i = 0; i < 1000; i++)
   {
      result = result + sin(i*tid) * tan(i*tid);
   }
   printf("Thread %ld done. Result = %e\n", tid, result);
   pthread_exit((void*) t);
}

void pthread_create_with_stack( pthread_t * pthread, void *(*start_routine) (void *), int tid )
{
    const size_t STACKSIZE = 0xC00000; //12582912
    int rc;
    size_t i;
    pid_t pid;

    stackAddr[tid] = malloc(STACKSIZE);
    pthread_attr_setstack(&attr, stackAddr[tid], STACKSIZE);

    rc = pthread_create( pthread, &attr, start_routine, (void*)0 );
}

int main (int argc, char *argv[])
{
   int rc;
   long t;
   void *status;

   /* Initialize and set thread detached attribute */
   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

   for(t=0; t<NUM_THREADS; t++) 
   {
      printf("Main: creating thread %ld\n", t);
      // The following line is the line 52, where error occurs
      rc = pthread_create_with_stack( &thread[t], BusyWork, t ); 
      if (rc) 
      {
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }

   /* Free attribute and wait for the other threads */
   pthread_attr_destroy(&attr);
   for(t=0; t<NUM_THREADS; t++) 
   {
      rc = pthread_join(thread[t], &status);
      if (rc) 
      {
         printf("ERROR; return code from pthread_join() is %d\n", rc);
         exit(-1);
      }
      printf("Main: completed join with thread %ld having a status"   
            "of %ld\n",t,(long)status);
    }

    printf("Main: program completed. Exiting.\n");
    pthread_exit(NULL);
}
Run Code Online (Sandbox Code Playgroud)

jwo*_*der 10

pthread_create_with_stack返回void,但你试图将这个void"值" 保存在一个int,这是一个错误.

  • 公平地说,编译器警告实际上非常接近描述情况...... (4认同)

Pat*_*k87 5

就是这条线

rc = pthread_create_with_stack( &thread[t], BusyWork, t );
Run Code Online (Sandbox Code Playgroud)

您对pthread_create_with_stack的定义是void类型.应该是void*类型并返回rc,这是pthread_create()的结果.

由于pthread_create_with_stack是一个void函数,并且它在定义中没有返回任何内容,因此将rc设置为其返回值不仅没有意义,这是一个错误,gcc/g ++甚至不会让你尝试编译.