#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
void printf_id(const char *name)
{
pid_t pid, ppid;
pthread_t tid;
pid = getpid();
ppid = getppid();
tid = pthread_self();
printf("%s pid = %d ppid = %d tid = %u ox%x\n", name, pid, ppid, tid, tid);
}
void *pthread_proc(void *arg)
{
printf_id("new pthread");
pthread_exit((void*)NULL);
}
int main(int argc, char **argv)
{
pthread_t tid;
int err;
err = pthread_create(&tid, NULL, pthread_proc, NULL);
if(err != 0)
{
printf("pthread_create :%s\n", strerror(err));
return -1;
}
printf_id("main pthread");
err = pthread_join(tid, (void *)NULL);
if(err != 0)
{
printf("pthread_join :%s\n", strerror(err));
return -1;
}
return 0;
}
./a.out (执行结果如下)
main pthread pid = 25368 ppid = 17795 tid = 3069550592 oxb6f5a000
new pthread pid = 25368 ppid = 17795 tid = 3068322928 oxb6e2e470
疑问:
观察程序执行结果,与apue2上面所描述的Linux下执行结果有两点差别:
o 这里两个线程的pid相同(说明是同一个进程)
而书中所叙述的是:Linux使用clone系统调用来实现pthread_create,clone用于创建
子进程。按书所说,主线程和新线程的pid应该不同(书上的结果确实是不同pid)。
o Linux里pthread_t实现为unsigned long int,但这里打印出来的线程ID值看起来十六
进制的表示更有意义些,这是为何?