我使用以下代码创建两个线程:
//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 语法是否正确。我是否需要发出其他命令来编译该文件?
编辑:在上面的代码中创建两个线程有什么问题吗?该程序一旦运行就会退出并显示错误消息。可能出现的问题是什么以及如何解决?提前致谢。
尝试这样做:
gcc -lpthread sample.c
or
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)您在 while(1) 中调用 pthread_create 这将创建无限线程..我不知道您想实现什么目标。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)