千家信息网

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

发表于:2026-11-01 作者:千家信息网编辑
千家信息网最后更新 2026年11月01日,零散知识。1.线程id--- 进程id的类型是pid_t, 线程id的类型是pthread_t;比较两个线程id:#include int pthread_equal ( pthread_t tid1
千家信息网最后更新 2026年11月01日unix高级环境编程---11章 线程 学习

零散知识。

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);
}

线程 类型 编译 接下来 两个 例子 再次 属性 工程 文件 知识 进程 提示 运行 选择 高级 环境 学习 编程 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 互联网科技公司简介 广州淘业互联网络科技 科技股互联网 科技信息互联网 深圳科技互联网 中盈科技互联网信息有限公司 中国的互联网科技企业的崛起 央行互联网金融科技公司 北京华百购互联网科技有限公司 荆州市昕露互联网络科技有限公司 国大互联网教育科技有限公司工作 中国科技创新与世界互联网大会 互联网科技和法律行业 黑科技 体验场景 互联网大会 深圳互联网科技的发展 昆明中奇联合互联网科技 互联网科技机房 互联网企业和网络科技有限公司 中国主要互联网科技公司 山东亿川互联网科技有限责任公司 科技互联网公司logo 科技伦理 互联网公司 深圳市运趣互联网科技有限公司 茂名市互联网科技产业园 港股科技和互联网 厦门千工互联网科技有限公司 注册互联网科技公司经营范围大全 链环科技传统企业怎么转型互联网 张召忠谈中国互联网科技 互联网科技自媒体灵感
0