关于线程创建的接口问题

q198816 2008-11-07 08:07:39
  1 #include "apue.h"
2 #include <pthread.h>
3
4 pthread_t ntid;
5
6 void
7 printids(const char *s)
8 {
9 pid_t pid;
10 pthread_t tid;
11
12 pid = getpid();
13 tid = pthread_self();
14 printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid,
15 (unsigned int)tid, (unsigned int)tid);
16 }
17
18 void *
19 thr_fn(void *arg)
20 {
21 printids("new thread: ");
22 return((void *)0);
23 }
24
25 int
26 main(void)
27 {
28 int err;
29
30 err = pthread_create(&ntid, NULL, thr_fn, NULL);
31 if (err != 0)
32 err_quit("can't create thread: %s\n", strerror(err));
33 printids("main thread:");
34 sleep(1);
35 exit(0);
36 }


我的系统fedora 9 编译器 GCC4.3
提示如下

/tmp/ccyszIni.o: In function `main':
q.c:(.text+0x536): undefined reference to `pthread_create'
collect2: ld 返回 1



我又看了下man 说明是linux提供的实现接口可能不同.......
This manual page is part of the POSIX Programmer’s Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual
page for details of Linux behavior), or the interface may not be implemented on Linux.





到底是怎么回事?是linux内核原因?还是GCC版本原因?


在我的这个环境下pthread_create这个进程创建的接口函数如何实现?
请大侠详细解释下





~
...全文
93 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
ilovedrv 2008-11-08
  • 打赏
  • 举报
回复
这个是连接错误,就是说找不到pthread_create的符号表,所以在编译连接是要加上-lpthread
快乐田伯光 2008-11-07
  • 打赏
  • 举报
回复
Linux是提供这个接口的, 你提供的那段文字是说, Linux的实现这个接口的方式可能不一样. Linux没为线程直接提供系统调用接口, 是通过对就不同实现方法的各种posix线程库实现的, 所以编译的时候需要把pthread线程库给链接进去. 方法如楼上各件所说.

至于你说的pthread_create是如何实现的,看你的内核版本,2.4及以前通过linuxthread库实现, 2.6通过nptl实现, 实际内部都调用了系统调用clone(), 通过设置不同的flag达到创建线程的目的, 具体你可以去man一下clone,就会发现一些有趣的调用flag.
joyself 2008-11-07
  • 打赏
  • 举报
回复
假设你的源文件是 test.c

gcc -o test test.c -lpthread
cloudflashes 2008-11-07
  • 打赏
  • 举报
回复
编译的时候没有把pthread的库链上。
wuyu637 2008-11-07
  • 打赏
  • 举报
回复
g++ -lpthread xxx.o -o xxxx

你没有加编译参数把。??
xhs_lh04 2008-11-07
  • 打赏
  • 举报
回复
-pthread

23,120

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧