关于Pthread线程编译的问题

系统安装、升级讨论
版面规则
我们都知道新人的确很菜,也喜欢抱怨,并且带有浓厚的Windows习惯,但既然在这里询问,我们就应该有责任帮助他们解决问题,而不是直接泼冷水、简单的否定或发表对解决问题没有任何帮助的帖子。乐于分享,以人为本,这正是Ubuntu的精神所在。
回复
szweifj
帖子: 2
注册时间: 2011-07-29 13:40

关于Pthread线程编译的问题

#1

帖子 szweifj » 2011-12-20 14:38

wei@wei-machine:~/5/code$ gcc -o thread thread.c

/tmp/ccwLelgL.o: In function `main':

thread.c:(.text+0xa7): undefined reference to `pthread_create'

thread.c:(.text+0xef): undefined reference to `pthread_create'

thread.c:(.text+0x126): undefined reference to `pthread_join'

thread.c:(.text+0x13a): undefined reference to `pthread_join'

collect2: ld returned 1 exit status

用GCC编译后出现上述错误,不知道是怎么回事,是因为Pthread.h头文件吗?如何解决?谢谢!
源代码如下:
thread.c:
#include <stdio.h>
#include <pthread.h>

void thread1(void)
{
int i=0;
for(i=0;i<6;i++)
{
printf("This is a pthread1.\n");
if(i==2)
pthread_exit(0);
sleep(1);
}
}

void thread2(void)
{
int i;
for(i=0;i<3;i++)
printf("This is a pthread2.\n");
pthread_exit(0);
}

int main(void)
{
pthread_t id1,id2;
int i,ret;
ret=pthread_create(&id1,NULL,(void *) thread1,NULL);
if(ret!=0)
{
printf ("Create pthread error!\n");
exit (1);
}
ret=pthread_create(&id2,NULL,(void *) thread2,NULL);
if(ret!=0)
{
printf ("Create pthread error!\n");
exit (1);
}
pthread_join(id1,NULL);
pthread_join(id2,NULL);
exit (0);
}
szweifj
帖子: 2
注册时间: 2011-07-29 13:40

Re: 关于Pthread线程编译的问题

#2

帖子 szweifj » 2011-12-20 14:42

刚查到原因了 呵呵

由于pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,在编译中要加 -lpthread参数。
回复