嵌入式——线程
🛑线程
一个进程可以有多个线程,他们共享这个进程资源
早期的操作系统都是以进程作为独立运行的基本单位的,直到后期计算机科学家们又提出了更小的能独立运行的基本单位,也就是线程。
线程又称为迷你进程,但是它比进程更容易创建,也更容易撤销
用严谨的语言描述来说就是:由于创建或撤销进程时,系统都要为之分配或回收资源,如内存空间、I/O 设备等,需要较大的时空开销,限制了并发程度的进一步提高。为减少进程切换的开销,把进程作为资源分配单位和调度单位这两个属性分开处理,即进程还是作为资源分配的基本单位,但是不作为调度的基本单位(很少调度或切换),把调度执行与切换的责任交给线程,即线程成为独立调度的基本单位,它比进程更容易(更快)创建,也更容易撤销。
🍃线程优缺点
线程的特征和进程差不多,进程有的他基本都有,比如:
- 线程具有就绪、阻塞、运行三种基本状态,同样具有状态之间的转换关系
- 线程间可以并发执行
- 在多 CPU 环境下,各个线程也可以分派到不同的CPU 上并行执行
线程的优点
- 一个进程中可以同时存在多个线程,这些线程共享该进程的资源。进程间的通信必须请求操作系统服务(因为 CPU要切换到内核态),开销很大。而同进程下的线程间通信,无需操作系统干预,开销更小
不过,需要注意的是:从属于不同进程的线程间通信,也必须请求操作系统服务- 线程间的并发比进程的开销更小,系统并发性提升
同样,需要注意的是:从属于不同进程的线程间切换,它是会导致进程切换的,所以开销也大
线程的缺点
- 当进程中的一个线程奔溃时,会导致其所属进程的所有线程奔溃
🍃创建线程
头文件:
#include <pthread.h>
函数原型:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
函数功能:创建线程,把pid线程和参数3start_routine绑定起来
函数参数:
函数参数1:pthread_t pid &pid创建的线程是谁
函数参数2:指定线程的属性,一般传NULL
函数参数3:线程执行的工作,是一个函数指针,指向的函数的数据类型是void * (void *)
函数参数4:传递给线程执行的参数
函数返回值:成功返回0,失败返回-1
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//线程1执行函数
void *Func_1(void *argv)
{
while(1)
{
printf("采集环境声\n");
sleep(1);
}
}
void *Func_2(void *arg)
{
for( ; ; )
{
printf("和互联网进行链接\n");
sleep(1);
}
}
int main(int argc, const char *argv[])
{
//定义变量
pthread_t pid_1, pid_2;
//创建线程
pthread_create(&pid_1, NULL, Func_1, NULL);//pthread_t * , NULL, 函数指针, void *arg
pthread_create(&pid_2, NULL, Func_2, NULL);
while(1)
{
printf("控制显示\n");
sleep(1);
}
return 0;
}
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//线程1执行函数
void *Func_1(void *argv)
{
while(1)
{
printf("采集环境声\n");
sleep(1);
}
}
void *Func_2(void *arg)
{
for( ; ; )
{
printf("和互联网进行链接\n");
sleep(1);
}
}
int main(int argc, const char *argv[])
{
//定义变量
pthread_t pid_1, pid_2;
//创建线程
pthread_create(&pid_1, NULL, Func_1, NULL); //pthread_t * , NULL, 函数指针, void*arg
pthread_create(&pid_2, NULL, Func_2, NULL);
int i = 0;
while(1)
{
printf("控制显示\n");
sleep(1);
if(i++ == 15)
{
break;
}
}
printf("主线程退出\n");
return 0;
}
🍃线程的结束
🌿主动结束
头文件:
#include<stdio,h>
函数原型:
void pthread_exit(void *retval);
函数参数:
value_ptr 线程退出时返回的值
函数返回值:
成功:0
失败:-1
🌿被动结束
头文件:
#include <pthread.h>
函数原型:
int pthread_cancel(pthread_t thread);
函数参数:
thread 要取消的线程
函数返回值:
成功:0
失败:-1
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//线程1执行函数
void *Func_1(void *argv)
{
int i = 0;
while(1)
{
if(i++ == 10)
{
printf("线程1将要主动退出!!!\n");
pthread_exit(NULL);//主动退回,没有返回值
}
printf("采集环境声\n");
sleep(1);
}
}
void *Func_2(void *arg)
{
for( ; ; )
{
printf("和互联网进行链接\n");
sleep(1);
}
}
int main(int argc, const char *argv[])
{
//定义变量
pthread_t pid_1, pid_2;
//创建线程
pthread_create(&pid_1, NULL, Func_1, NULL); //pthread_t * , NULL, 函数指针, void*arg
pthread_create(&pid_2, NULL, Func_2, NULL);
int i = 0;
while(1)
{
printf("控制显示\n");
sleep(1);
if(i++ == 13)
{
//取消线程2的任务
printf("线程2被动退出!!!!\n");
pthread_cancel(pid_2);
}
}
printf("主线程退出\n");
return 0;
}
🍃回收线程资源
🌿阻塞回收
头文件:
#include<stdio.h>
函数原型:
int pthread_join(pthread_t thread, void **value_ptr)
函数参数:
thread:要等待的线程
value_ptr:指针*value_ptr指向线程返回的参数
函数返回值:
成功:0
失败:-1
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//线程1执行函数
void *Func_1(void *argv)
{
int i=0;
while(1)
{
if(i++ == 15)
{
pthread_exit(NULL);
}
printf("采集环境声\n");
sleep(1);
}
}
void *Func_2(void *arg)
{
for( ; ; )
{
printf("和互联网进行链接\n");
sleep(1);
}
}
int main(int argc, const char *argv[])
{
//定义变量
pthread_t pid_1, pid_2;
//创建线程
pthread_create(&pid_1, NULL, Func_1, NULL); //pthread_t * , NULL, 函数指针, void*arg
pthread_create(&pid_2, NULL, Func_2, NULL);
int i = 0;
pthread_join(pid_1, NULL);//阻塞等待指定的线程,
// join(pthread_t pid, *);
while(1)
{
printf("控制显示\n");
sleep(1);
if(i++ == 5)
{
break;
}
}
printf("主线程退出\n");
return 0;
}
🌿不阻塞回收
头文件:
#include <pthread.h>
函数原型:
int pthread_detach(pthread_t thread);
把主线程和指定的thread线程剥离
作用:从状态上实现线程分离,注意不是指该线程独自占用地址空间。
线程分离状态:指定该状态,线程主动与主控线程断开关系。线程结束后〈不会产生僵尸线程),具退出认念个出只化或性次大以,且这自己自动释放(自己清理掉PCB的残留资源)。网络、多线程一服务器常用。
进程若有该机制,将不会产生僵尸进程。僵尸进程的产生主要由于进程死后,大部分资源被释放,一点残留资源仍存于系统中,导致内核认为该进程仍存在。(注意进程没有这一机制)
🌿线程之间的数据传输
验证:除了栈区之外的数据,都是共享的:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
static int c = 20;
//线程1执行函数
void *Func_1(void *argv)
{
printf("c = %d\n", c);
c+=20;
int *p = (int *)argv;
int i=0; //局部变量
while(1)
{
if(i++ == 15)
{
*p = 15 ;
pthread_exit(NULL);
}
printf("采集环境声\n");
sleep(1);
}
}
void *Func_2(void *arg)
{
for( ; ; )
{
printf("和互联网进行链接\n");
sleep(1);
}
}
int main(int argc, const char *argv[])
{
int *p = NULL;
p = (int *) malloc(sizeof(int)); //堆区
*p = 0;
printf("*p = %d\n", *p);
//定义变量
pthread_t pid_1, pid_2;
//创建线程
pthread_create(&pid_1, NULL, Func_1, p); //pthread_t * , NULL, 函数指针, void*arg
pthread_create(&pid_2, NULL, Func_2, NULL);
int i = 0; //主线程的局部变量
while(1)
{
printf("控制显示\n");
sleep(1);
if(i++ == 5)
{
break;
}
}
printf("主线程退出\n");
printf("c = %d \n", c);
pthread_join(pid_1, NULL);
printf("*p = %d\n", *p);
return 0;
}
🍃主线程给子线程传递数据
通过pthrad_create的第四个参数
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//线程1执行函数
void *Func_1(void *arg)
{
//str1 ==> arg
char *pstr = (char *)arg; //传过来的是什么类型的数据
//要转换成一样类型的
printf("线程1:%s\n", pstr);
pthread_exit(NULL);
}
void *Func_2(void *arg)
{
//str2 ==> arg
char *pstr = (char *)arg; //传过来的是什么类型的数据
//要转换成一样类型的
printf("线程2:%s\n", pstr);
pthread_exit(NULL);
}
void *Func_3(void *arg)
{
//str3 ==> arg
char *pstr = (char *)arg; //传过来的是什么类型的数据
//要转换成一样类型的
printf("线程3:%s\n", pstr);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//在栈区定义变量
char str1[20] = "ABCDEFG";
char str2[20] = "abcdefg";
char str3[20] = "0123456";
//定义变量
pthread_t pid_1, pid_2, pid_3;
//创建线程
pthread_create(&pid_1, NULL, Func_1, str1); //pthread_t * , NULL, 函数指针, void*arg
pthread_create(&pid_2, NULL, Func_2, str2);
pthread_create(&pid_3, NULL, Func_3, str3);
//阻塞等待线程退出
pthread_join(pid_1, NULL);
pthread_join(pid_2, NULL);
pthread_join(pid_3, NULL);
return 0;
}
🍃子线程给主线程传递数据
通过pthread_exit()传递
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
//线程1执行函数
void *Func_1(void *arg)
{
//str1 ==> arg
char *pstr = (char *)arg; //传过来的是什么类型的数据
//要转换成一样类型的
char *ps = (char *)malloc(sizeof(char) * 50);
memset(ps, 0, sizeof(char)*50);
strcat(ps, pstr);
strcat(ps, "xiancheng1");
//printf("线程1:%s\n", pstr);
pthread_exit(ps);
}
void *Func_2(void *arg)
{
//str2 ==> arg
char *pstr = (char *)arg; //传过来的是什么类型的数据
//要转换成一样类型的
char *ps = (char *)malloc(sizeof(char) * 50);
memset(ps, 0, sizeof(char)*50);
strcat(ps, pstr);
strcat(ps, "xiancheng2");
//printf("线程2:%s\n", pstr);
pthread_exit(ps);
}
void *Func_3(void *arg)
{
//str3 ==> arg
char *pstr = (char *)arg; //传过来的是什么类型的数据
//要转换成一样类型的
char *ps = (char *)malloc(sizeof(char) * 50);
memset(ps, 0, sizeof(char)*50);
strcat(ps, pstr);
strcat(ps, "xiancheng3");
//printf("线程3:%s\n", pstr);
pthread_exit(ps);
}
int main(int argc, const char *argv[])
{
//在栈区定义变量
char str1[20] = "ABCDEFG";
char str2[20] = "abcdefg";
char str3[20] = "0123456";
char *ps1 = NULL;
char *ps2 = NULL;
char *ps3 = NULL;
//定义变量
pthread_t pid_1, pid_2, pid_3;
//创建线程
pthread_create(&pid_1, NULL, Func_1, str1); //pthread_t * , NULL, 函数指针, void*arg
pthread_create(&pid_2, NULL, Func_2, str2);
pthread_create(&pid_3, NULL, Func_3, str3);
//阻塞等待线程退出
pthread_join(pid_1, (void **)&ps1); //void ** ps1 char *
pthread_join(pid_2, (void **)&ps2);
pthread_join(pid_3, (void **)&ps3);
//在主线程使用值
printf("ps1 = %s\n", ps1);
printf("ps2 = %s\n", ps2);
printf("ps3 = %s\n", ps3);
return 0;
}
🍃互斥
引入互斥(mutual exclusion)锁的目的是用来保证共享数据操作(临界资源)的完整性。
互斥锁主要用来保护临界资源
每个临界资源都由一个互斥锁来保护,任何时刻最多只能有一个线程能访问该资源
线程必须先获得互斥锁才能访问临界资源,访问完资源后释放该锁。如果无法获得锁,线程会阻塞直到获得锁为止
🌿定义互斥锁
pthread_mutex_t mutex_1;
//要给多个线程访问,所以得定义在共享的地方,全局变量
🌿初始化锁
头文件:
#include<pthread.h>
函数原型:
int pthread_mutex_init(pthread_mutex_t *mutex, pthread_mutexattr_t *attr)
函数参数:
mutex:互斥锁
attr:互斥锁属性//NULL表示缺少属性
函数返回值:
成功:0
失败:-1
🌿上锁
头文件:
#include<pthread.h>
函数原型:
int pthread_mutex_lock(pthread_mutex_t *mutex)
函数参数:
mutex:互斥锁
函数返回值:
成功:0
失败:-1
🌿释放锁
头文件:
#include<pthread.h>
函数原型:
int pthread_mutex_unlock(pthread_mutex_t *mutex)
函数参数:
mutex:互斥锁
函数返回值:
成功:0
失败:-1
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
//定义互斥锁
pthread_mutex_t mymutex;
char str[20] = {0}; //共享的资源,每一个线程都能访问到
//线程1执行函数
void *Func_1(void *arg)
{
int i = 0;
//str1 ==> arg
char *pstr = (char *)arg; //传过来的是什么类型的数据
//要转换成一样类型的
//上锁
pthread_mutex_lock(&mymutex);
//要将pstr指示的数据,放到str里面
while(pstr[i] != '\0')
{
str[i] = pstr[i];
printf("str = %s\n", str);
sleep(1);
i++;
}
str[i] = '\0';
printf("str = %s\n", str);
//释放锁
pthread_mutex_unlock(&mymutex);
pthread_exit(NULL);
}
void *Func_2(void *arg)
{
int i = 0;
//str2 ==> arg
char *pstr = (char *)arg; //传过来的是什么类型的数据
//要转换成一样类型的
//上锁
pthread_mutex_lock(&mymutex);
//要将pstr指示的数据,放到str里面
while(pstr[i] != '\0')
{
str[i] = pstr[i];
printf("str = %s\n", str);
sleep(1);
i++;
}
str[i] = '\0';
printf("str = %s\n", str);
//释放锁
pthread_mutex_unlock(&mymutex);
pthread_exit(NULL);
}
void *Func_3(void *arg)
{
int i = 0;
//str3 ==> arg
char *pstr = (char *)arg; //传过来的是什么类型的数据
//要转换成一样类型的
//上锁
pthread_mutex_lock(&mymutex);
//要将pstr指示的数据,放到str里面
while(pstr[i] != '\0')
{
str[i] = pstr[i];
printf("str = %s\n", str);
sleep(1);
i++;
}
str[i] = '\0';
printf("str = %s\n", str);
//释放锁
pthread_mutex_unlock(&mymutex);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//在栈区定义变量
char str1[20] = "ABCDEFG";
char str2[20] = "abcdefg";
char str3[20] = "0123456";
//初始化锁
pthread_mutex_init(&mymutex, NULL);
//定义变量
pthread_t pid_1, pid_2, pid_3;
//创建线程
pthread_create(&pid_1, NULL, Func_1, str1); //pthread_t * , NULL, 函数指针, void *arg
pthread_create(&pid_2, NULL, Func_2, str2);
pthread_create(&pid_3, NULL, Func_3, str3);
//阻塞等待线程退出
pthread_join(pid_1, NULL); //void ** ps1 char *
pthread_join(pid_2, NULL);
pthread_join(pid_3, NULL);
//销毁锁
pthread_mutex_destroy(&mymutex);
return 0;
}
🍃同步
同步(synchronization)指的是多个任务(线程) 按照约定的顺序相互配合完成一件事情
🌿定义信号量
sem_t mysem;
🌿初始化信号量
头文件:
#include<semaphore.h>
函数原型:
int sem_init(sem_t *sem, int pshared, unsigned int value)
函数参数:
sem: 初始化的信号量
pshared:信号量共享的范围(0:线程间使用 非0:进程间使用)
value:信号量初值
函数返回值:
成功:0
失败:-1
🌿pv操作
头文件:
#include<semaphore.h>
函数原型:
int sem_wait(sem_t *sem) // P操作
函数参数:
sem:信号量
函数返回值:
成功:0
失败:-1
P操作:
- P(S) 含义如下:
- 可用:申请资源的任务继续运行;信号量的值减一
- 不可用:申请资源的任务阻塞
头文件:
#include<semaphore.h>
函数原型:
int sem_post(sem_t *sem) // V操作
函数参数:
sem:信号量
函数返回值:
成功:0
失败:-1
V操作:
- V(S) 含义如下:
- 没有任务在等待该资源,信号量的值加一
- 唤醒第一个等待的任务,让其继续运行
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
//定义信号量
sem_t sem_1,sem_2;
//线程1的执行函数
void *Func_1(void *arg)
{
while(1)
{
//P
sem_wait(&sem_1);
printf("我生产了一台电脑\n");
sleep(1);
//V
sem_post(&sem_2);
}
}
//线程2的执行函数
void *Func_2(void *arg)
{
while(1)
{
//P
sem_wait(&sem_2);
printf("我买了一台电脑\n\n\n");
sleep(1);
//V
sem_post(&sem_1);
}
}
int main(int argc, const char *argv[])
{
pthread_t pid_1, pid_2;
//信号量初始化
//sem_init(sem_t *, int , int );
sem_init(&sem_1, 0, 1);
sem_init(&sem_2, 0, 0);
//创建两个进程
pthread_create(&pid_1, NULL, Func_1, NULL);
pthread_create(&pid_2, NULL, Func_2, NULL);
//等待
pthread_join(pid_1, NULL);
pthread_join(pid_2, NULL);
return 0;
}
🍃线程池
任务执行的时间有可能远远低于线程创建和销毁的时间,可以搞一个线程池(不销毁的,同步做的)
设计思路
实现线程池有以下几个步骤:
- 设置一个生产者消费者队列,作为临界资源。
- 初始化n个线程,并让其运行起来,加锁去队列里取任务运行
- 当任务队列为空时,所有线程阻塞。
- 当生产者队列来了一个任务后,先对队列加锁,把任务挂到队列上,然后使用条件变量去通知阻塞中的一个线
程来处理。
线程池中线程数量:
- 线程数量和哪些因素有关:CPU,IO、并行、并发
- 如果是CPU密集型应用,则线程池大小设置为:CPU数目+1
- 如果是IO密集型应用,则线程池大小设置为:2*CPU数目+1
- 最佳线程数目 = (线程等待时间与线程CPU时间之比 + 1)* CPU数目
所以线程等待时间所占比例越高,需要越多线程。线程CPU时间所占比例越高,需要越少线程。
为什么要创建线程池:
创建线程和销毁线程的花销是比较大的,这些时间有可能比处理业务的时间还要长。这样频繁的创建线程和销毁线程,再加上业务工作线程,消耗系统资源的时间,可能导致系统资源不足。同时线程池也是为了提升系统效率。
线程池的核心线程与普通线程:
任务队列可以存放100个任务,此时为空,线程池里有10个核心线程,若突然来了10个任务,那么刚好10个核心线程直接处理;若又来了90个任务,此时核心线程来不及处理,那么有80个任务先入队列,再创建核心线程处理任务;若又来了120个任务,此时任务队列已满,不得已,就得创建20个普通线程来处理多余的任务。 以上是线程池的工作流程。