Chinaunix首页 | 论坛 | 博客
  • 博客访问: 71581
  • 博文数量: 28
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 291
  • 用 户 组: 普通用户
  • 注册时间: 2013-11-29 14:47
文章存档

2014年(13)

2013年(15)

我的朋友

分类: C/C++

2013-12-11 13:59:53

得到一个线程ID pthread_t pthread_self(void);  #include
判断两个线程的ID是否相等
int pthread_equal(pthread_t tid1,pthread_t tid2);
创建一个线程 成功返回0 错误返回错误编码
int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr,void *(*start_rtn)(void),void *restrict arg);
pthread_create函数的第一个参数tidp是一个pthread_t类型的指针,当该函数返回时,tidp指向内核分配给线程的ID。第二个参数attr表示线程的属性,如果不想特别的指定线程属性可以设置为NULL。
pthread_create函数的第三个参数start_rtn是一个函数指针,其所指向函数的返回值是一个void类型的指针,参数也是一个void类型的指针。start_rtn所指向的函数是线程的主题,也就是pthread_create函数创建出来的线程从start_rtn所指向的函数的起始地址开始执行,当该函数返回时该线程就停止运行了。第4个参数arg是一个void类型的指针,arg是start_rtn所指向的函数的参数,在线程开始执行时,该参数有内核负责传递给线程。
#include
#include
#include

void* thfn(void* arg)
{
  pid_t pid;
  pthread_t tid;

  pid=getpid();
  tid=pthread_self();

  printf("the new thread:pid is: %u,tid is: %u\n",(unsigned int)pid,(unsigned int)tid);
  return NULL;
}
int main(void)
{
  pid_t pid;
  int err;
  pthread_t tid,mtid;

  pid=getpid();
  mtid=pthread_self();
  err=pthread_create(&tid,NULL,thfn,NULL);//问题出在这里原来我搞错了,这是创建新的线程
  if(err!=0){
    printf("cannot create thread %s\n",strerror(err));
    exit(1);
  }
  /*休眠一秒钟,保证新创建的线程在主线程之前被调用*/
  sleep(1);
  printf("the main thread:pid is: %u,tid is: %u\n",(unsigned int)pid,(unsigned int)tid);//tid应该改为mtid才对
  return 0;
}
输入:
gcc printtid.c -o printtid -lpthread
结果:为什么主线程和创建的线程ID一样???
the new thread:pid is: 2524,tid is: 3078511472
the main thread:pid is: 2524,tid is: 3078511472

#include
#include
#include
#include
typedef struct arg_struct ARG;

struct arg_struct{
  char arg1[10];
  int arg2;
  float arg3;
};
/*线程体*/ 无法执行到这里???? 因为主线程退出了,需要在主线程中增加waitfor等待创建的线程或者sleep
void* thfn(void *arg)
{
  ARG *p=(ARG*)arg;/*强制类型转换,将arg转换为指向ARG类型变量的指针*/
  printf("*************\n");
  printf("arg1 is: %s,arg2 is: %d,arg3 is: %f\n",p->arg1,p->arg2,p->arg3);
  return NULL;
}
int main(int argc,char *argv[])
{
  pthread_t tid;
  ARG arg;

  strcpy(arg.arg1,argv[1]);
  arg.arg2=atoi(argv[2]);
  arg.arg3=atof(argv[3]);
  printf("%s,%d,%f\n",arg.arg1,arg.arg2,arg.arg3);
  int err=pthread_create(&tid,NULL,thfn,(void*)&arg);
  if(err!=0){
    printf("can not create thread %s\n",strerror(err));
    exit(1);
  }
  return 0;
}

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