在线pthread程序没有编译

时间:2016-01-14 13:01:11

标签: c pthreads

online program如何在编译期间使用pthread提供错误

我确信我做错了,但我已经编译并运行该网站的其他程序。

我使用 gcc -pthread -o hello thread.c 命令编译程序。 有什么想法吗?

编译报告:

thread.c: In function ‘Hello’:
thread.c:23:24: warning: incompatible implicit declaration of built-in function ‘sin’ [enabled by default]
      result = result + sin(i) * tan(i);
                        ^
thread.c:23:33: warning: incompatible implicit declaration of built-in function ‘tan’ [enabled by default]
      result = result + sin(i) * tan(i);
                                 ^
thread.c:25:4: warning: format ‘%ld’ expects argument of type ‘long int’, but argument 2 has type ‘void *’ [-Wformat=]
    printf("%ld: Hello World!\n", threadid);
    ^
thread.c: In function ‘main’:
thread.c:38:5: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
     printf("Code %d= %s\n",rc,strerror(rc));
     ^
/tmp/ccmix2XI.o: In function `Hello':
thread.c:(.text+0x33): undefined reference to `sin'
thread.c:(.text+0x42): undefined reference to `tan'
collect2: error: ld returned 1 exit status

1 个答案:

答案 0 :(得分:1)

它会抱怨,因为您没有包含math.h并且没有与数学库建立链接。

包含`并编译为:

gcc -o hello thread.c -pthread -lm

您还需要:

#include <string.h>  # for strerror() function
#include <unistd.h>  # for sleep() function

您需要在printf()中将void*转换为long

   printf("%ld: Hello World!\n", (long)threadid);

请注意,此整数转换指针是实现定义。理想情况下,您应该将指针传递给long并将其强制转换回long*并取消引用它。它可以通过以下方式修改:

#include <math.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NTHREADS        32

void *Hello(void *threadid)
{
   int i;
   double result=0.0;
   long my_id = *(long*)threadid;
   sleep(3);

   for (i=0; i<10000; i++) {
     result = result + sin(i) * tan(i);
   }

   printf("%ld: Hello World!\n", my_id);
   pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
   pthread_t threads[NTHREADS];
   int rc;
   long t;
   long a[NTHREADS];

   for(t=0;t<NTHREADS;t++){
      a[t] = t;
      rc = pthread_create(&threads[t], NULL, Hello, &a[t]);
      if (rc){
         printf("ERROR: return code from pthread_create() is %d\n", rc);
         printf("Code %d= %s\n",rc,strerror(rc));
         exit(-1);
      }
   }

   printf("main(): Created %ld threads.\n", t);
   pthread_exit(NULL);
}