1、概念
线程也是一个并发的执行流程,一般称之为轻量级的进程;线程是cpu最小的执行单元
线程从属于创建它的进程,不和进程分离,共享进程资源;
创建线程的进程结束了,则该进程创建的所有线程都结束;线程结束,不会影响进程。
2、线程的结束方式
①线程函数执行完,运行return返回;
②线程运行过程中,满足某个条件提前结束,用pthread_exit函数
③与进程同归于尽,在线程中调用exit函数结束进程
④线程A收到线程B发送的结束请求,默认情况下,会执行结束请求,提前结束程序
线程结束处理:线程有运行的代码、栈空间、TCB(线程控制块)、线程号。。。,线程结束后,需要对其进行资源回收;
pthread_join函数:阻塞等待指定的线程结束,并对其进行资源回收,可以获得线程返回值
3、用例
#include <pthread.h>
void *thread_one(void *arg)
{
int num = (int)arg;
while (num>0)
{
printf("in thread one --> %d\n", num--);
sleep(1);
if (2 == num)
{
//结束线程本身,不会其其他线程和进程产生影响
//pthread_exit((void*)88);
//结束进程,进程结束了,所有线程也就结束了
exit(EXIT_SUCCESS);
}
}
return NULL;
}
int main(void)
{
//线程标识变量
pthread_t one; //long unsigned int;
//参数二:设置线程的属性,分离线程,线程栈空间大小,优先级,调度测略...
//参数三:线程执行函数
//返回值:成功为0,失败为错误编号
//参数二默认NULL,表示非分离线程,需要pthread_join阻塞等待
int ret = pthread_create(&one, NULL, thread_one, (void*)10);
if (0 != ret)
{
printf("create thread one failed --> %s\n", strerror(ret));
exit(EXIT_FAILURE);
}
printf("pthread_one=%lu\n", one);
//阻塞等待指定的线程结束,并对其进行资源回收
void *retval = NULL;
pthread_join(one, &retval);
printf("thread retval = %d\n", (int)retval);
//进程称之为主线程
int i = 0;
while (1)
{
printf("in main while --> %d\n", ++i);
sleep(1);
}
return 0;
}
4、函数介绍
①pthread_detach() 设置分离线程
设置线程为分离线程,分离的线程结束后,其资源自动归还给系统,
不需要其他线程调用pthread_join回收,若为分离线程,join函数不会阻塞
②pthread_cancel()发送结束请求
在线程或函数调用 pthread_cancel(one);//向指定的线程发送结束请求
线程函数接收请求并处理
void *thread_one(void *arg)
{
int i = 0;
//收到的结束请求将会被阻塞,直到cancel state设置为enable
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
while (1)
{
printf("in thread one --> %d\n", ++i);
sleep(1);
if (15 == i)
{
printf("15s解除阻塞,cancel state设置为enable...\n");
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
}
}
return (void*)66;
}
③创建线程是传入线程属性参数,同①类似
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_t one; //long unsigned int;
int ret = pthread_create(&one, &attr, thread_one, NULL);
④线程中设置线程分离,函数同①,但主函数在pthread_join前sleep(1)等待一下才能生效
⑤设置线程优先级,同③
pthread_attr_t attr;
pthread_attr_init(&attr);
//pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
struct sched_param param;
param.sched_priority = 3;
int errnum = pthread_attr_setschedparam(&attr, ¶m);
if (0 != errnum)
{
printf("设置优先级失败-->%s\n", strerror(errnum));
exit(EXIT_FAILURE);
}
pthread_t one; //long unsigned int;
int ret = pthread_create(&one, &attr, thread_one, NULL);