pthread_create编译时返回错误

时间:2012-05-18 10:51:26

标签: c linux pthreads

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

//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语法是正确的。我是否必须发出一些其他命令来编译文件?

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

3 个答案:

答案 0 :(得分:4)

尝试这样做:

gcc -lpthread sample.c

gcc -pthread sample.c

以上2个命令将直接创建可执行文件a.out

编辑后回答:

1)等待两个线程使用call

加入主线程
int pthread_join(pthread_t thread, void **value_ptr);

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

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

4)你正在调用pthread_create而while(1)这将创建无限的线程..我不知道你想要实现什么。

答案 1 :(得分:2)

编译时链接到pthread库...

gcc -o sample -lpthread sample.c

答案 2 :(得分:0)

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

的事情
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。但是在线程之间共享变量等时要小心。但很高兴你自己解决了。

相关问题