源代码:
:cat -n 11_2.c
1 #include "apue.h"
2 #include <pthread.h>
3
4 pthread_t ntid;
5
6 void printids(char *pstr)
7 {
8 pid_t pid;
9 pthread_t tid;
10
11 pid = getpid();
12 tid = pthread_self();
13
14 printf("%s:pid = %lu\t tid = %lu\t (0x%lx)\n",pstr,(unsigned long) pid, (unsigned long) tid, (unsigned long) tid);
15 }
16
17
18
19 void * thr_fn(void *arg)
20 {
21 printids("new thread");
22 return ((void *) 0 );
23 }
24
25
26 int main(void)
27 {
28 int err;
29 err = pthread_create(&ntid,NULL,thr_fn,NULL);
30
31 if (err != 0)
32 err_sys("can't create thread.Error Number:%d",err);
33
34 printids("main");
35 sleep(1);
36 exit(0);
37
38
39 }
uname -a
SunOS bldc 5.8 Generic_Virtual sun4u sparc SUNW,Netra-T12
在SunOS上pthread_create 创建失败。
gcc -Wall -ggdb3 11_2.c error.c -lpthread -o printids
./printids
can't create thread.Error Number:-1: Error 0
原因:pthread库不是Linux系统默认的库,连接时需要使用静态库libpthread.a,所以在线程函数在编译时,需要连接库函数!
编译:
gcc -Wall -ggdb3 11_2.c error.c -o printids -lpthread
error.c: In function `err_doit':
error.c:121: warning: implicit declaration of function `vsnprintf'
error.c:123: warning: implicit declaration of function `snprintf'
运行结果:
./printids
main:pid = 4540 tid = 1 (0x1)
new thread:pid = 4540 tid = 2 (0x2)