- #include <stdio.h>
- #include <pthread.h>
- #include <stdlib.h>
- 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);
- }
- void *
- thr_fn(void *arg)
- {
- printids(“new thread:”);
- return ((void *)0);
- }
- int
- main()
- {
- pthread_t ntid;
- int err;
- err = pthread_create(&ntid, NULL, thr_fn, NULL);
- if(err != 0)
- printf(“不能创建线程[%s]\n”,strerror(err));
- printids(“main thread:”);
- sleep(3);
- exit(0);
- }
[root@localhost pthread]# gcc test.c -o test
/tmp/ccq2Mbxs.o: In function `main’:
test.c:(.text+0x89): undefined reference to `pthread_create’
collect2: ld 返回 1
[root@localhost pthread]#
问题原因:
pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。
问题解决:
在编译中要加 -lpthread参数
gcc test.c -o test -lpthread
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/163102.html