《APUE》:打印线程ID


《Unix环境高级编程》这本书附带了许多短小精美的小程序,我在阅读此书的时候,将书上的代码按照自己的理解重写了一遍(大部分是抄书上的),加深一下自己的理解(纯看书太困了,呵呵)。此例子在Ubuntu 10.04上测试通过。

相关链接

  • 《UNIX环境高级编程》(第二版)apue.h的错误
  • Unix环境高级编程 源代码地址

程序简介:以下这个程序创建一个线程并且打印进程ID,新线程的ID以及初始线程的线程的ID

  1. //《APUE》程序11-1:创建一个子线程并打印其线程ID   
  2. #include <unistd.h>   
  3. #include <stdio.h>   
  4. #include <stdlib.h>   
  5. #include <pthread.h>   
  6.   
  7. pthread_t ntid;  
  8.   
  9. void printfids(const char *s)  
  10. {  
  11.     //打印当前线程的进程ID和线程ID   
  12.     pid_t pid = getpid();  
  13.     pthread_t tid = pthread_self();  
  14.   
  15.     printf("%s pid %u tid %u (0x%x)\n",s, (unsigned int)pid,  
  16.         (unsigned int)tid, (unsigned int)tid);  
  17. }  
  18.   
  19. void *thr_fn(void *arg)  
  20. {  
  21.     printfids("new thread: ");  
  22.     return (void*)0;  
  23. }  
  24.   
  25. int main(void)  
  26. {  
  27.     pthread_create(&ntid, NULL, thr_fn, NULL);  
  28.     printfids("main thread: ");  
  29.     //让主线程睡眠1秒钟,这是保证子线程可以运行的一种权宜之计   
  30.     sleep(1);  
  31.     return 0;  
  32. }  

运行示例(红色字体的为输入):

www.bkjia.com @ubuntu:~/code$ gcc temp.c -lpthread -o temp 
www.bkjia.com @ubuntu:~/code$ ./temp
main thread:  pid 4153 tid 3078440640 (0xb77d46c0)
new thread:  pid 4153 tid 3078437744 (0xb77d3b70)

相关内容