笔记8 linux多线程编程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hjj651471519/article/details/80178741
线程(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:不执行 (执行上面的指定函数)


猜你喜欢

转载自blog.csdn.net/hjj651471519/article/details/80178741