你好,游客 登录 注册 搜索
背景:
阅读新闻

《APUE》:打印线程ID

[日期:2012-09-14] 来源:Linux社区  作者:AAA20090987 [字体:大 中 小]

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

相关链接

程序简介:以下这个程序创建一个线程并且打印进程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.linuxidc.com @ubuntu:~/code$ gcc temp.c -lpthread -o temp 
www.linuxidc.com @ubuntu:~/code$ ./temp
main thread:  pid 4153 tid 3078440640 (0xb77d46c0)
new thread:  pid 4153 tid 3078437744 (0xb77d3b70)

linux
相关资讯       APUE 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款