在pthread_create的编译错误回报(pthread_create return error

2019-09-17 08:06发布

我用下面的代码创建两个线程:

//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

我应该怎么做才能正确编译该文件。 我相信这是因为当我评论过的一切,而循环,程序正确编译内,我验证了在pthread_create语法是正确的没有语法错误或任何东西。 我一定要发出一些其他的命令编译文件?

编辑:有两个线程在上面的代码产生任何问题吗? 这个计划只是与错误信息一旦退出正在运行。 有什么可以可能的问题,我该怎么解决呢? 提前致谢。

Answer 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)此外,还要避免从主()如果可以调用pthread_exit,虽然没有害处这样做

4)您呼叫的同时,在pthread_create(1),这将创造无限的主题。我不知道什么是你想要的目的。



Answer 2:

链接编译时并行线程库...

的gcc -o样品-lpthread sample.c文件



Answer 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);

我认为它应该给你的ID 2线程。 但仔细共享变量时等线程之间。 但是,很高兴你自己解决吧。



文章来源: pthread_create return error on compiling
标签: c linux pthreads