温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-05-01 01:00:27 来源:网络 阅读:1005 作者:zz_yun 栏目:系统运维

零散知识。

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

比较两个线程id:

#include <pthread.h>

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 <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
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);
}
 

 

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI