【问题标题】:creating threads in C [duplicate]在C中创建线程[重复]
【发布时间】:2013-03-13 16:10:28
【问题描述】:

我正在尝试使用 gcc -Wall -std=c99 hilo.c - ./a.out hilo.c 运行此 C 程序,但收到以下错误消息:

hilo.c: In function ‘func’:
hilo.c:6:3: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘pthread_t’ [-Wformat]
hilo.c: In function ‘main’:
hilo.c:14:3: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [enabled by default]
/usr/include/pthread.h:225:12: note: expected ‘void * (*)(void *)’ but argument is of type ‘void (*)(void)’
hilo.c:15:3: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [enabled by default]
/usr/include/pthread.h:225:12: note: expected ‘void * (*)(void *)’ but argument is of type ‘void (*)(void)’
hilo.c:24:3: warning: statement with no effect [-Wunused-value]
/tmp/cchmI5wr.o: In function `main':
hilo.c:(.text+0x52): undefined reference to `pthread_create'
hilo.c:(.text+0x77): undefined reference to `pthread_create'
hilo.c:(.text+0x97): undefined reference to `pthread_join'
hilo.c:(.text+0xab): undefined reference to `pthread_join'
collect2: ld returned 1 exit status

不知道代码有什么问题,所以如果有人可以帮助我,将不胜感激。

这是代码:

#include <pthread.h>
#include <stdio.h>

void func(void){

         printf("thread %d\n", pthread_self());
         pthread_exit(0);

}

   int main(void){

        pthread_t hilo1, hilo2;

        pthread_create(&hilo1,NULL, func, NULL);
        pthread_create(&hilo2,NULL, func, NULL);

        printf("the main thread continues with its execution\n");

        pthread_join(hilo1,NULL);
        pthread_join(hilo2, NULL);

        printf("the main thread finished");

        scanf;

  return(0);

}

【问题讨论】:

  • @MichaelBurr:很遗憾,但如果其他问题的答案不正确,我不想将其标记为重复。
  • @Dietrich:太糟糕了,没有某种社区/版主/任何替代方案来覆盖 SO 上的已接受答案(我想有人可能会争辩说投票数应该如此)。我们还没有看到这里是否接受了正确的答案。

标签: c pthreads undefined-reference


【解决方案1】:

改变

void func(void)

void* func(void *)

并用

编译
gcc hilo.c -pthread

您只会在打印pthread_self() 时出错,因为它不是int

【讨论】:

    【解决方案2】:

    你应该编译和链接-pthread

    gcc -Wall -std=c99 hilo.c -pthread
    

    使用-lpthread 是不够的。 -pthread 标志将改变一些 libc 函数的工作方式,以使它们在多线程环境中正常工作。

    【讨论】:

    • 您的答案取决于平台。在 some 上,-pthread 是必要的,即使我怀疑在这种情况下您是正确的。并不是每个支持 pthreads 的系统都是这样的。
    【解决方案3】:

    您尚未链接 pthread 库。编译:

    gcc -Wall -std=c99 hilo.c -lpthread
    

    【讨论】:

    • 我还应该补充一点,这是一种 POSIX 方式来链接 any 库 (-l)。而在 pthreads 的情况下,它是编译器和 libc 相关的情况,即当使用 -pthread 时 gcc 设置了可能无法使用 -lpthread 设置的附加选项/开关(甚至可能导致 libc 的错误功能)。这在很大程度上是 gcc 特定的。更一般的答案是:在可用时使用-pthread。如果没有,请使用-lpthread 通过阅读其文档,确保设置平台/编译器正常运行所需的任何其他选项/编译器开关。
    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 2020-04-18
    • 2021-12-09
    相关资源
    最近更新 更多