您的位置:首页 > Web前端

关于线程编程中“undefined reference to 'pthread_create'等问题的解决

2015-01-04 14:35 513 查看
今天学习UNIX环境高级编程第11章中的线程编程,在编译第一个demo时,出现了“undefined reference to ‘pthread_create’”这种错误导致无法编译通过。

问题的原因:pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。

解决:在gcc编译的时候,命令加上 -lpthread参数即可解决。

程序11-1.c

#include "apue.h"
#include <pthread.h>

pthread_t ntid;

static void printids(const char *);
static void *func(void*);

int main(void)
{
int err;

err = pthread_create(&ntid, NULL, func, NULL);
if(err != 0)
err_quit("can't create thread: %s\n",strerror(err));
printids("main thread: ");
sleep(1);
exit(0);
}

static void printids(const char *s)
{
pid_t pid;
pthread_t tid;

pid = getpid();
tid = pthread_self();

printf("%s pid %u tid %u (0x%x)\n",s,(unsigned int)pid,(unsigned int)tid,(unsigned int)tid);
}

static void *func(void *arg)
{
printids("new thread: ");
return((void*)0);
}


编译和运行:

[root@localhost 11]# gcc 11-1.c -lpthread
[root@localhost 11]# ./a.out
main thread: pid 5362 tid 3086317248 (0xb7f576c0)
new thread: pid 5362 tid 3086314384 (0xb7f56b90)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: