【问题标题】:pthread_create return error on compilingpthread_create 编译时返回错误
【发布时间】:2012-05-18 10:51:25
【问题描述】:

我使用以下代码创建了两个线程:

//header files
#include <pthread.h>
struct thread_arg
{
    int var1;
    int var2;
};
void *serv_com(void *pass_arg)
{
    struct thread_arg *con = pass_arg;
    //required statements irrelevant to the issue
    pthread_exit(NULL);
}
void *cli_com(void *pass_arg)
{
    struct thread_arg *con = pass_arg;
    //required statements irrelevant to the issue
    pthread_exit(NULL);
}
int main()
{
    pthread_t inter_com;
    //necessary code
    while(1)
    {
        th_err_s = pthread_create(&inter_com, NULL, serv_com, (void *)&pass_arg);
        th_err_c = pthread_create(&inter_com, NULL, cli_com, (void *)&pass_arg);
        if (th_err_s || th_err_c)
        {
            printf("Alert! Error creating thread! Exiting Now!");
            exit(-1);
        }
    }
    pthread_exit(NULL);
    return 1;
}

然后我在linux中使用以下命令编译了上面的代码:

gcc -o sample sample.c

它返回以下错误消息:

inter.c:(.text+0x374): undefined reference to `pthread_create'
inter.c:(.text+0x398): undefined reference to `pthread_create'
collect2: ld returned 1 exit status

我应该怎么做才能正确编译这个文件。我确信这不是语法错误或任何东西,因为当我注释掉 while 循环中的所有内容时,程序正在正确编译并且我验证了 pthread_create 语法是正确的。我必须发出其他命令来编译文件吗?

编辑:在上面的代码中创建两个线程有​​什么问题吗?程序一旦运行就会退出并显示错误消息。可能是什么问题,我该如何解决?提前致谢。

【问题讨论】:

标签: c linux pthreads


【解决方案1】:

尝试这样做:

gcc -lpthread sample.c

gcc -pthread sample.c

以上2条命令将直接创建可执行的a.out

编辑后回答:

1) 等待两个线程调用加入主线程

int pthread_join(pthread_t thread, void **value_ptr);

2) 创建具有不同 id 的两个线程

3) 如果可以的话,也要避免从 main() 调用 pthread_exit,尽管这样做并没有什么坏处

4) 你在 while(1) 中调用 pthread_create 这将创建无限线程.. 我不知道你想达到什么目的。

【讨论】:

  • 没有其他线程。这是两个独立的线程。
  • 这两个独立线程在主线程退出时退出,因此除非这两个线程已完成工作,否则请避免退出主线程,我将编辑我的答案
  • 这个答案有点疑问。我从while(1) 内部调用两个线程,从外部调用pthread_exit()。那么pthread_exit() 会如何影响pthread_create() 的功能呢?
【解决方案2】:

编译时链接到 pthread 库...

gcc -o 示例 -lpthread 示例.c

【讨论】:

    【解决方案3】:

    我自己也不太确定,但我认为你可以做类似的事情

    pthread_t inter_com, inter_com2;
    

    th_err_s = pthread_create(&inter_com, NULL, serv_com, (void *)&pass_arg);
            th_err_c = pthread_create(&inter_com2, NULL, cli_com, (void *)&pass_arg);
    

    我认为它应该为您提供 2 个线程 ID。但是在线程之间共享变量等时要小心。但很高兴你自己解决了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      相关资源
      最近更新 更多