一、线程的创建
这个程序让主进程 启动一个线程, 主进程和线程都打印一次 PID(进程ID)和TID(线程ID)。
#include "apue.h"
#include <pthread.h>
pthread_t ntid;
void printids(const char *s){
pid_t pid;
pthread_t tid;
pid = getpid(); //获取进程id
tid = pthread_self(); //获取自己的线程id
printf("%s pid %lu tid %lu (0x%lx)\n", s,(unsigned long)pid,
(unsigned long)tid, (unsigned long)tid);
}
void *thr_fn(void *arg){
printids("new thread: ");
return ((void *)0);
}
int main(void){
int err;
//ntid是线程ID所指单元, attr定制线程属性, thr_fn就是线程执行函数。
err = pthread_create(&ntid, NULL, thr_fn, NULL);
if( err != 0)
err_exit(err, "can't create thread");
printids("main thread:"); //主进程输出自己的2个ID
//休眠,防止主进程先结束。
sleep(1);
exit(0);
}
1.为什么要休眠? 避免主进程先于线程退出。 当主进程终止时,就会发送信号给各个线程,使他们一起终止。
2. 线程获取自己ID时,能否通过ntid来获取自己的相关内容?
不可以, 因为当进程调用pthread_create时, thr_fn就会启动, 如果thr_fn执行较快,在pthread_create返回前就结束了, ,即当它返回时才会设置ntid,故很可能会来不及使用。
3. Linux下线程ID是无符号长整形。
二、线程的退出