gpt4 book ai didi

c - 在线 pthread 程序无法编译

转载 作者:行者123 更新时间:2023-11-30 15:13:13 26 4
gpt4 key购买 nike

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

最佳答案

它提示是因为您没有包含 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);
}

关于c - 在线 pthread 程序无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34790323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com