网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

unix高级环境编程---11章线程学习

零散知识。

成都创新互联企业建站,10年网站建设经验,专注于网站建设技术,精于网页设计,有多年建站和网站代运营经验,设计师为客户打造网络企业风格,提供周到的建站售前咨询和贴心的售后服务。对于网站设计、成都网站制作中不同领域进行深入了解和探索,创新互联在网站建设中充分了解客户行业的需求,以灵动的思维在网页中充分展现,通过对客户行业精准市场调研,为客户提供的解决方案。

1.线程id---     进程id的类型是pid_t, 线程id的类型是pthread_t;

比较两个线程id:

#include

int pthread_equal ( pthread_t tid1, pthread_t tid2 );

获得自身的线程id:

pthread_t pthread_self(void)

2.线程创建

int pthread_create( pthread_t *restrict tidp, const pthread_attr_t *restrict attr,

     void *(*start_rtn)(void *),  void *restrict arg );

 接下来是打印线程id的例子:

#include
#include
#include
#include
#include
#include
pthread_t ntid;

void printids(const char *s){
 pid_t pid;
 pthread_t tid;
 pid = getpid();
 tid = pthread_self();
 printf("%s pid %u tid %u (0x%x)\n",s, (unsigned int)pid,
   (unsigned int)tid, (unsigned int) tid);

}
void *thr_fn(void *arg){
 printids("new thread: ");
 return ((void*)0);

}

int main(){
 int err = 0;
 err = pthread_create(&ntid, NULL, thr_fn, NULL);
 //err = pthread_create(&ntid, NULL, thr_fn, NULL);
 if(err!=0){
  printf("%s\n", strerror(err) );

 }
 printids("main thread:");
 sleep(1);
 exit(0);
}
 

 

使用ubuntu,eclipse编译,提示找不到pthread_create.  头文件是定义了,但是没有连接线程库。 需要设置eclipse。 选择工程--属性--c、c++build--settings---gcc c linker---libraries, 添加库 pthread。  再次编译运行。ok。

main thread: pid 2164 tid 3079145152 (0xb78806c0)
new thread:  pid 2164 tid 3079142256 (0xb787fb70)
 

 3、线程终止

void *thr_fn1(void *arg){
 printf("thread 1 returning\n");
 return ((void* )1);

}

void *thr_fn2(void *arg){
 printf("thread 2 exiting\n");
 pthread_exit((void *)1);

}

int main(){
 int err;
 pthread_t tid1, tid2;
 void  *tret;
 err = pthread_create(&tid1, NULL, thr_fn1, NULL);
 if( err != 0){
  printf("can't create thread 1:%s\n", strerror(err));
 }
 err = pthread_create(&tid2, NULL, thr_fn2, NULL);
 if( err!=0){
  printf("can't create thread 2:%s\n", strerror(err));
 }
 err = pthread_join(tid1, &tret);
 if(err!=0){
  printf("can't join with thread 1:%s\n", strerror(err));

 }
 printf(" thread 1 exit code %d\n", (int)tret);
 err = pthread_join(tid2, &tret);
 if(err!=0){
  printf("can't join eith thread 2:%s\n", strerror(err));
 }
 printf("thread 2 exit code %d\n", (int)tret);
 exit(0);
}
 

 


网页题目:unix高级环境编程---11章线程学习
网站地址:http://bjjierui.cn/article/gscphd.html

其他资讯