【问题标题】:undefined reference to pthread_wait compiled with -pthread & -lpthread对使用 -pthread 和 -lpthread 编译的 pthread_wait 的未定义引用
【发布时间】:2014-10-06 08:18:23
【问题描述】:

我收到以下错误:

assign4.o: In function `main':
assign4.c:(.text+0x76f): undefined reference to `pthread_broadcast'
assign4.o: In function `threadFunc':
assign4.c:(.text+0x15fd): undefined reference to `pthread_wait'
assign4.c:(.text+0x17f3): undefined reference to `pthread_wait'
collect2: ld returned 1 exit status

编译时:

gcc -pthread assign4.c -o assign4 -lm

gcc assign4.c -o assign4 -lm -lpthread

这是对 pthread_broadcast 的调用:

while (killCount < numThreads) {
    while (waitCount < numThreads);
    waitCount = 0;
    pthread_broadcast();
}

对 pthread_wait 的调用:

pthread_wait();
for (i = 0; i < partInfo.groupSize; i++) {  
    for (j = 0; j < numParts; j++) {
        gravitation(bodies[i], parts[i]);
    }
}
if (pthread_mutex_lock(&mtx) != 0) {
    printf("Error locking mutex.\n");
    return -1;
}
waitCount++;
if (pthread_mutex_unlock(&mtx) != 0) {
    printf("Error unlocking mutex.\n");
    return -1;
}
pthread_wait();
if (pthread_mutex_lock(&mtx) != 0) {
    printf("Error locking mutex.\n");
    return -1;
}

如您所见,我尝试使用 -pthread 和 -lpthread 进行编译,但无法正常工作。我想这一定是我错过了一些非常明显的东西,但我不知道是什么。

提前谢谢你!

【问题讨论】:

  • 我正在使用一个学校服务器,它必须能够在其上进行编译,并且其他人已经成功地在该服务器上编译了 pthread 程序。这是 gcc -v 信息:使用内置规范。目标:x86_64-redhat-linux 配置: 线程模型:posix gcc version 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC)
  • -Wall打开编译器警告,GCC会告诉你pthread_waitpthread_broadcast还没有被声明。

标签: c gcc compilation pthreads


【解决方案1】:

如果你想在进入线程后等待一段时间,你可以尝试使用 sleep();并提供秒数作为参数。如果这不起作用,请尝试 pthread_cond_wait(); 可以参考pthread tutorials

是的,因为没有 pthread_wait() 这样的函数,所以会抛出编译错误。

【讨论】:

    【解决方案2】:

    您确定不是在寻找pthread_cond_broadcastpthread_cond_wait

    似乎没有任何 pthread_waitpthread_broadcast 函数,尤其是不带参数的函数。

    【讨论】:

      【解决方案3】:

      没有名为pthread_wait()的函数,它可能是pthread_cond_wait()。这就是您收到链接器错误的原因。当链接器找不到函数定义时,它会给出undefined reference to 错误。所以你得到了

      assign4.c:(.text+0x15fd): undefined reference to `pthread_wait'
      assign4.c:(.text+0x17f3): undefined reference to `pthread_wait'
      

      我认为pthread_broadcast() 也是同样的错误,应该是pthread_cond_broadcast()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-25
        • 1970-01-01
        • 1970-01-01
        • 2015-10-23
        • 1970-01-01
        • 2016-05-02
        • 2013-06-12
        相关资源
        最近更新 更多