pthread_create编译时返回错误 [英] pthread_create return error on compiling

查看:73
本文介绍了pthread_create编译时返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have used the following code to create two threads:

//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中编译以上代码:

Then I compiled the above code in linux using the following command:

gcc -o sample sample.c

它返回了以下错误消息:

It returned the following error message:

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

What should I do to correctly compile this file. I am sure it is no syntax error or anything since when I commented off everything inside the while loop, the program was compiling correctly and I verified that the pthread_create syntax is correct. Do I have to issue some other command to compile the file?

在上面的代码中创建两个线程是否有问题?该程序在运行后只是退出并显示错误消息.可能是什么问题,我该如何解决?预先感谢.

Is there any problem with the creating of two threads in the above code? The program is just exiting with the error message once it is running. What can be the possible issue and how can I solve it? Thanks in advance.

推荐答案

尝试执行此操作:

gcc -lpthread sample.c

gcc -pthread sample.c

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

above 2 commands will directly create executable a.out

修改后答案:

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

1) Wait for the two threads to join main thread using call

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

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

2) Create both threads with different ids

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

3) Also avoid calling pthread_exit from main() if you can, although there is no harm doing that

4)您正在while(1)中调用pthread_create,这将创建无限线程..我不知道您要实现什么目标.

4) you are calling pthread_create in while(1) this will create infinite threads .. I do not know what are you trying to achieve .

这篇关于pthread_create编译时返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆