Linux-线程

线程

一、线程概述

1.1 - 线程的概念

  • 在一个程序里的多个执行路线就叫做线程(thread)。更准确的定义是:线程是“一个进程内部的控制序列
  • 一切进程至少都有一个执行线程

1.2 - fork和创建新线程的区别

  • 当一个进程执行一个fork调用的时候,会创建出进程的一个新拷贝,新进程将拥有它自己的变量和它自己的PID。这个新进程的运行时间是独立的,它在执行时几乎完全独立于创建它的进程
  • 在进程里面创建一个新线程的时候,新的执行线程会拥有自己的堆栈(因此也就有自己的局部变量),但要与它的创建者共享 全局变量文件描述符信号处理器当前的子目录状态

1.3 - 线程的优点

  • 提高程序的并发性
  • 开销小,不用重新分配内存
  • 通信和共享数据方便

1.4 - 线程的缺点

  • 线程不稳定(库函数实现)
  • 线程调试比较困难(gdb支持不好)
  • 线程无法使用unix经典事件,例如信号

二、线程常用函数

2.1 - pthread_create 函数

函数原型

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
						void *(*start_routine) (void *), void *arg);

函数功能: 创建线程
头文件

#include <pthread.h>

参数说明

  • pthread_t *thread:传递一个pthread_t变量地址进来,用于保存新线程的tid(线程ID)

  • const pthread_attr_t *attr:线程属性设置,如使用默认属性,则传NULL

  • void *(*start_routine) (void *):函数指针,指向新线程应该加载执行的函数模块

  • void *arg:指定线程将要加载调用的那个函数的参数

返回值:

  • 成功返回0,失败返回错误号。以前学过的系统函数都是成功返回0,失败返回-1,而错误号保存在全局变量errno中,而pthread库的函数都是通过返回值返回错误号,虽然每个线程也都有一个errno,但这是为了兼容其它函数接口而提供的,pthread库本身并不使用它,通过返回值返回错误码更加清晰。

在一个线程中调用pthread_create()创建新的线程后,当前线程从pthread_create()
返回继续往下执行,而新的线程所执行的代码由我们传给 pthread_create的函数指针start_routine决定。

pthread_create 函数应用示例

#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
void *thrd_func(void *arg)
{
	int i = (int)arg;
	sleep(i);
	printf("%d ,in thread : thread id = %lu,pid = %u \n",i+1,pthread_self(),getpid());
	
	return NULL;
}

int main(void)
{
	pthread_t tid;
	int ret,i;
	//pthread_self()函数获取当前线程tid,getpid()获取当前进程pid();
	printf("in main : thread id = %lu,pid = %u \n",pthread_self(),getpid());
	for(i=0; i<5; i++)
	{
		//创建一个新线程,去执行thrd_func()函数,
		//原来线程继续往下执行
		ret = pthread_create(&tid,NULL,thrd_func,(void*)i);
		if(ret)//创建进程失败
		{
			printf("pthread_create error \n");
			exit(1);
		}
	}
	sleep(1);
	
	return 0;
}

运行结果

2.2 - pthread_exit 函数

函数原型

void pthread_exit(void *retval);

函数功能: 结束调用了这个函数的线程
头文件

#include <pthread.h>

参数说明

  • void *retval:线程退出时传递出的参数,可以是退出值或地址,如是地址时,不能是线程内部申请的局部地址。

调用线程退出函数,注意和exit函数的区别,任何线程里exit导致进程退出,其他线程未工作结束,主控线程退出时不能return或exit。
需要注意,pthread_exit或者return返回的指针所指向的内存单元必须是全局的或者是用malloc分配的,不能在线程函数的栈上分配,因为当其它线程得到这个返回指针时线程函数已经退出了。

2.3 - pthread_join 函数

函数原型

int pthread_join(pthread_t thread, void **retval);

函数功能: 调用该函数的线程将挂起等待,直到idthread的线程终止。
头文件

#include <pthread.h>

参数说明

  • pthread_t thread:回收线程的tid
  • void **retval:接收退出线程传递出的返回值

返回值:成功返回0,失败返回错误号

调用该函数的线程将挂起等待,直到id为thread的线程终止。thread线程以不同的方法终止,通过pthread_join得到的终止状态是不同的,总结如下

  • 如果thread线程通过return返回,retval所指向的单元里存放的是thread线程函数的返回值
  • 如果thread线程被别的线程调用pthread_cancel异常终止掉,retval所指向的单元里存放的是常数PTHREAD_CANCELED
  • 如果thread线程是自己调用pthread_exit终止的,retval所指向的单元存放的是传给pthread_exit的参数
  • 如果对thread线程的终止状态不感兴趣,可以传NULL给retval参数。

pthread_join 函数应用示例

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

typedef struct 
{
	int a;
	int b;
	
}exit_t;

void *thrd_func(void *arg)
{
	exit_t *ret;
	ret = (exit_t *)malloc(sizeof(ret));
	ret->a = 100;
	ret->b = 200;
	
	pthread_exit((void *)ret);
}

int main(void)
{
	pthread_t tid;
	exit_t *retval;
	int ret;
	ret = pthread_create(&tid,NULL,thrd_func,NULL);
	if(ret)
	{
		printf("pthread_create error \n");
		exit(1);
	}
	//pthread_join函数会阻塞原来的主线程
	//直到tid 的线程结束后,解除阻塞状态
	pthread_join(tid,(void **)&retval);
	
	printf("a=%d,b=%d\n",retval->a,retval->b);
	
	sleep(1);
	return 0;
}


运行结果

2.4 - pthread_cancel函数

函数原型

int pthread_cancel(pthread_t thread);

函数功能: 它发送终止信号给thread线程
头文件

#include <pthread.h>

参数说明

  • pthread_t thread:要取消线程的tid

返回值:如果成功则返回0,否则为非0值

2.5 - pthread_detach函数

函数原型

int pthread_detach(pthread_t tid);

函数功能: 分离线程,一个分离的线程是不能被其他线程回收或杀死的,它的存储器资源在它终止时由系统自动释放。
头文件

#include <pthread.h>

参数说明

  • pthread_t thread:分离线程tid

返回值:成功返回0,失败返回错误号。

一般情况下,线程终止后,其终止状态一直保留到其它线程调用pthread_join获取它的状态为止。但是线程也可以被置为detach状态,这样的线程一旦终止就立刻回收它占用的所有资源,而不保留终止状态。不能对一个已经处于detach状态的线程调用pthread_join,这样的调用将返回EINVAL。如果已经对一个线程调用了pthread_detach就不能再调用pthread_join了。

pthread_detach函数应用示例

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
void *thr_fn(void *arg) {
	int n = 3;
	while (n--) {
		printf("thread count %d\n", n);
		sleep(1);
	}
	return (void *)1;
}
int main(void) {
	pthread_t tid;
	void *tret;
	int err;
	pthread_create(&tid, NULL, thr_fn, NULL);
   //第一次运行时注释掉下面这行,第二次再打开,分析两次结果
	pthread_detach(tid);
	while (1) {
		err = pthread_join(tid, &tret);
		if (err != 0)//调用join函数失败
			fprintf(stderr, "thread1 %s\n", strerror(err));
		else//调用join函数成功
			fprintf(stderr, "thread2 exit code %d\n", (int)tret);
		sleep(1);
	}
	return 0;
}

运行结果(注释掉 pthread_detach(tid);时)

在这里插入图片描述

运行结果(没有注释掉 pthread_detach(tid);时)

可以看出 当对创建的的线程调用 pthread_detach函数时,pthread_join便不再起到阻塞原来线程的作用,而是直接返回错误号

三、线程的三种退出方式

如果需要只终止某个线程而不终止整个进程,可以有三种方法:

  • 1.从线程主函数return。这种方法对主控线程不适用,从main函数return相当于调用exit。
  • 2.一个线程可以调用pthread_cancel终止同一进程中的另一个线程。
  • 3.线程可以调用pthread_exit终止自己。

三种退出方式应用示例

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
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 *)2);
}
void *thr_fn3(void *arg) {
   while(1) {
   	printf("thread 3 writing\n");
   	sleep(1);
   }
}
int main(void) {
   pthread_t tid;
   void *tret;
   pthread_create(&tid, NULL, thr_fn1, NULL);
   pthread_join(tid, &tret);
   printf("thread 1 exit code %d\n", (int)tret);
   pthread_create(&tid, NULL, thr_fn2, NULL);
   pthread_join(tid, &tret);
   printf("thread 2 exit code %d\n", (int)tret);
   pthread_create(&tid, NULL, thr_fn3, NULL);
   sleep(3);
   pthread_cancel(tid);
   pthread_join(tid, &tret);
   printf("thread 3 exit code %d\n", (int)tret);
   return 0;
}

运行结果

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值