Chinaunix首页 | 论坛 | 博客
  • 博客访问: 538788
  • 博文数量: 156
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1183
  • 用 户 组: 普通用户
  • 注册时间: 2013-11-22 11:42
文章分类

全部博文(156)

文章存档

2015年(67)

2014年(89)

分类: 嵌入式

2015-04-13 16:50:32

一、线程的ID

pthread_t:结构体(FreeBSD5.2、Mac OS10.3)/unsigned long int(linux)
                /usr/include/bits/pthreadtypes.h

获取线程ID:pthread_self()
一个实例:获取主线程ID

点击(此处)折叠或打开

  1. #include "apue.h"

  2. int main()
  3. {
  4.     pid_t pid;
  5.     pthread_t tid;

  6.     pid = getpid();
  7.     tid = pthread_self();

  8.     printf("pid is %u, tid is %x\n", pid, tid);

  9.     return 0;
  10. }
思考:线程ID出了进程范围还有效吗?

二、创造新线程

int pthread_create(pthread_t *restrict tidp, 
                             const pthread_attr_t *restrict attr, 
                             void *(*start_routine)(void *), 
                             void *restrict arg)
第一个参数:新线程的id,如果成功则新线程的id回填充到tidp指向的内存
第二个参数:线程属性(调度策略,继承性,分离性...)
第三个参数:回调函数(新线程要执行的函数)
第四个参数:回调函数的参数
返回值:成功返回0,失败则返回错误码
编译时需要连接库libpthread

实例:创建线程,打印ID
程序框图


点击(此处)折叠或打开

  1. /*AUTHOR:    WJ
  2.  *DATE:        2015-3-18
  3.  *
  4.  *
  5.  *getpid()            获取进程ID
  6.  *pthread_self()    获取ID
  7.  *
  8.  *int pthread_create(pthread_t *thread,
  9.  *                     const pthread_attr_t *attr,
  10.  *                     void *(*start_routine) (void *),
  11.  *                 void *arg);
  12.  *第一个参数,新线程id,创建成功系统回填
  13.  *第二个参数,新线程到属性,NULL为默认属性
  14.  *第三个参数,新线程到启动函数
  15.  *第四个参数,传递给新线程
  16.  */
  17. #include "apue.h"

  18. void print_id(char *s)
  19. {
  20.     pid_t pid;
  21.     pthread_t tid;

  22.     pid = getpid();
  23.     tid = pthread_self();

  24.     printf("%s pid is %u, tid is 0x%x\n", s, pid, tid);

  25. }

  26. void *thread_fun(void *arg)
  27. {
  28.     print_id(arg);
  29.     return (void *)0;
  30. }

  31. int main()
  32. {
  33.     pthread_t ntid;
  34.     int err;

  35.     err = pthread_create(&ntid, NULL, thread_fun, "new thread");
  36.     if(err != 0 )
  37.     {
  38.         printf("create new thread failed\n");
  39.         return 0;
  40.     }
  41.     
  42.     print_id("main thread :");
  43.     sleep(2);

  44.     return 0;



  45. }

阅读(530) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~