笔记8 linux多线程编程

线程(thread ) < 进程

线程(thread ) -----> 依赖 <pthread.h> 和库 libpthread.a

①创建线程
int pthread_create(pthread_t * tidp,const pthread_attr_t *attr,void *(* start_rtn)(void),void *arg)
tidp:线程id
attr:线程属性(通常为空NULL)
strat_rtn:线程要执行的函数
arg:strat_rtn的参数

进行编译的时候要加上 -lpthread (因为需要libpthread.a库)
gcc filename -lpthread


#include <stdio.h>
#include <pthread.h>

void *myThread1(void)
{
int i;
for (i=0; i<100; i++)
{
printf("This is the 1st pthread,created by zieckey.\n");
sleep(1);//Let this thread to sleep 1 second,and then continue to run
}
}

void *myThread2(void)
{
int i;
for (i=0; i<100; i++)
{
printf("This is the 2st pthread,created by zieckey.\n");
sleep(1);
}
}

int main()
{
int i=0, ret=0;
pthread_t id1,id2;
/*创建线程1*/
ret = pthread_create(&id1, NULL, (void*)myThread1, NULL);
if (ret)
{
printf("Create pthread error!\n");
return 1;
}
/*创建线程2*/
ret = pthread_create(&id2, NULL, (void*)myThread2, NULL);
if (ret)
{
printf("Create pthread error!\n");
return 1;
}
pthread_join(id1, NULL);
pthread_join(id2, NULL);
return 0;
}



②终止线程
如果进程中任何一个线程中调用exit 或者 _exit,那么整个进程都会终止。线程退出的方式有:
1.线程从启动例程中返回 return
2.线程可以被另一个进程终止
3.线程自己调用pthread_exit函数
4.非正常终止,(例如:其他线程的干预,或者自身运行出错(如访问非法地址)而退出)
void pthread_exit(void * rval_ptr);
rval_ptr:线程退出后返回的指针
③线程等待
int pthrad_join(pthread_t tid,void ** rval_ptr)
功能:阻塞调用线程,直到线程终止。

④线程标识
pthread_t pthread_self(void)
功能:获取调用线程的 thread identifier 返回:TID


⑥线程非法终止时,清除占用空间
pthread_cleanup_push
pthread_cleanup_pop
在这对函数中间的代码,若出现非法终止,那么会执行pthread_cleanup_push所指定的清理函数, 不包括return.
void pthread_cleanup_push(void (*rtn)(void *),void *arg)
功能:将清除函数推入清除栈
rtn:清除函数 arg:清除函数的参数
void pthread_cleanup_pop(int execute)
功能:将清除函数弹出清除栈 execute 非0:执行 0:不执行 (执行上面的指定函数)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值