【1115】【多线程】【笔记】

多线程

bash 复制代码
意义 //多线程 共享资源,切换成本低 性能远高于 多进程,广泛用于Linux的应用开发中。 需重点掌握

API  // cat /usr/include/pthread.h |grep spin     
     // cat /usr/include/pthread.h |grep mutex
     // cat /usr/include/pthread.h |grep pthread

源码  //见 glibc-2.35/nptl
      //glibc里有很多应用层 C语言库的源码

注意 //多线程互斥,和内核类似,可看成是从内核层搬移到应用层
     //但线程库,尚不支持 顺序锁和RCU 

最简多线程

bash 复制代码
$ gcc pthread_base.c -lpthread -D_REENTRANT  /*编译程序
-lpthread : 链接pthread库( 原因是pthread不是Linux下的默认的库),不加会 报错undefined reference to `pthread_create' 
-D_REENTRANT: 生成可重入的程序
可重入函数: 多次进入同一函数(多线程执行该函数 或 自身调自身),输出一致。
条件: 不使用全局变量或静态变量,与硬件交互时要关终端
*/
$ ./a.out //可成功看到,并发执行(交替)

//pthread_base.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>  


//新线程入口(类似另一个app的main函数)
void  *task_camera(void *arg)
{
	int i;
	for (i=0; i<5; i++)
	{
		printf("camera task go\n");
		sleep(1);
	}
}


int main(int argc,  char *argv[])
{
	int ret;
	char num=3;
	pthread_t id_task_camera; //线程ID

	printf(" App Progress Start\n" );
	pthread_create(&id_task_camera, NULL, task_camera, NULL); //创建线程
	if(ret<0){  
		perror("pthread_create task_camera err\n");     
		exit(-1);
	}

	while(num--){
		printf(" main thread go \n");
		sleep(1);
	}

	pthread_join(id_task_camera, NULL); //等待子线程退出,回收其资源 
	printf(" App Progress End\n" );
	return 0;
}	

定义线程id

创建线程+新的线程入口

回收线程

互斥锁(量/体)

bash 复制代码
互斥锁: 用于线程互斥的二元变量  

动因 //线程引入共享了进程的地址空间,导致了一个线程操作数据时候,极其容易影响到其他线程的情况;
     //对其他线程造成不可控因素,或引起异常,逻辑结果不正确的情况;这也是线程不安全的原因.

别的线程会处在挂起状态;

最简

bash 复制代码
#include <stdio.h>
#include <pthread.h>

int count; //用全局变量,让线程间共享数据

pthread_mutex_t lock; //定义锁

void *pth_work(void *arg)
{
  while (1) {
    pthread_mutex_lock(&lock); //上锁( 不能获得时,会阻塞睡眠)
                              //trylock  尝试请求锁,锁不可用时,直接return,不会线程卡住
    count++;
    printf("pthread id=%d count=%d\n", pthread_self() , count); //pthread_self 获得线程自己的ID
    pthread_mutex_unlock(&lock); //解锁
    usleep(2000000);
  }
  return NULL;
}
void *pth_work2(void *arg)
{
  while (1) {
    pthread_mutex_lock(&lock);
    count=0;
    printf("pthread id=%d count=%d\n", pthread_self() , count); 
    pthread_mutex_unlock(&lock); 
    usleep(5000000);
  }
  return NULL;
}


int main(void)
{
  pthread_t id;  
  pthread_t id2;
  pthread_mutex_init(&lock, NULL); //构造锁

  //创建多个写线程
  pthread_create(&id, NULL, pth_work, NULL);
  pthread_create(&id2, NULL, pth_work2, NULL);
   
  //等待子线程退出,回收其资源    
  pthread_join(id, NULL);
  pthread_join(id2, NULL);
  pthread_mutex_destroy(&lock); //销毁锁
  return 0;
}	

多线程抢票

bash 复制代码
//对比:发现上锁前,票会出现负数,原因是 tickets-- 不是原子的,

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

int count; //用全局变量,让线程间共享数据
int tickets = 1000; // 票数(全局变量,线程间共享的数据)
pthread_mutex_t lock; //定义锁

void *pth_work(void *arg)
{
  while (1) {
    pthread_mutex_lock(&lock); //上锁( 不能获得时,会阻塞睡眠)
                        //trylock  尝试请求锁,锁不可用时,直接return,不会线程卡住
    if(tickets <=0){
    	printf(" no tickets\n ");
    	pthread_mutex_unlock(&lock); //解写锁
    	break;
    } 
    usleep(10000); //休眠10毫秒(模拟抢票准备时间)
    tickets--;//临界资源,模拟抢票,操作非原子的(汇编是有多行),不上锁时,会被多个线程改写,出现负数
    printf("pthread %d,my ticket is %d\n",pthread_self(),tickets); //pthread_self 获得线程自己的ID
    pthread_mutex_unlock(&lock); //解写锁
  }
  return NULL;
}


int main(void)
{
  pthread_t tid[5];
  pthread_mutex_init(&lock, NULL); //构造锁
  //创建多个写线程
  for(int i = 0;i < 5;i++){
    pthread_create(tid+i,NULL,pth_work,NULL);
  }

  //等待子线程退出,回收其资源  
  for(int i = 0; i< 5;i++){
    pthread_join(tid[i],NULL);
  }
  pthread_mutex_destroy(&lock); //销毁锁
  return 0;	

不加锁的时候,不是count=0原子操作;所以会被其他线程减多次

临界区资源上锁:

线程安全

bash 复制代码
线程安全: 争抢 临界资源 不造成 数据二义或逻辑混乱

线程不安全例子 //静态变量不上锁时
              
可重入函数 //被多线程调用,结果一致
           //可重入 一定是 线程安全的

信号量

bash 复制代码
//信号量和互斥锁 类似,简单修改即可
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

int count; //用全局变量,让线程间共享数据

sem_t sem; //定义信号量
void *pth_work(void *arg)
{
  while (1) {
    sem_wait(&sem);  //上锁(不能获得时,会阻塞睡眠)	
    count++;
    printf("pthread id=%d count=%d\n", pthread_self() , count); //pthread_self 获得线程自己的ID
    sem_post(&sem); //解锁
    usleep(2000000);
  }
  return NULL;
}
void *pth_work2(void *arg)
{
  while (1) {
    sem_wait(&sem);
    count=0;
    printf("pthread id=%d count=%d\n", pthread_self() , count); 
    sem_post(&sem);
    usleep(5000000);
  }
  return NULL;
}

int main(void)
{
  pthread_t id;  
  pthread_t id2;
  sem_init(&sem,0,1);  //构造二元信号量

  //创建多个写线程
  pthread_create(&id, NULL, pth_work, NULL);
  pthread_create(&id2, NULL, pth_work2, NULL);
   
  //等待子线程退出,回收其资源    
  pthread_join(id, NULL);
  pthread_join(id2, NULL);
  sem_destroy(&sem); //销毁信号量
  return 0;
}	

自旋锁

把互斥锁里示例, mutex 改为spin即可

但不能获得锁时 ,时自旋忙等待

读写锁

bash 复制代码
//pth_rwlock.c	
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

int counter; //用全局变量,让线程间共享数据

pthread_rwlock_t  rwlock; //读写锁

void *pth_write(void *arg)
{
  int t, i = (int)arg;
  while (1) {
    pthread_rwlock_wrlock(&rwlock); //上写锁(改写数据时,互斥所有)
              //上锁后,其它线程无法获得,将自旋忙等待(不睡眠)
    t = counter;
    usleep(1000);
    printf("write %d: %lu: counter=%d ++counter=%d\n", i, pthread_self(), t, ++counter); //pthread_self是获得线程ID
    pthread_rwlock_unlock(&rwlock); //解写锁
    usleep(10000);
  }
  return NULL;
}
void *pth_read(void *arg)
{
  int i = (int)arg;

  while (1) {
    pthread_rwlock_rdlock(&rwlock); //上读锁(除读读不互斥外,读写 写写要互斥)
    printf("read %d: %lu: %d\n", i, pthread_self(), counter); 
    pthread_rwlock_unlock(&rwlock); //解写锁
    usleep(2000);
  }
  return NULL;
}


int main(void)
{
  int i;
  pthread_t tid[6];
  pthread_rwlock_init(&rwlock, NULL); //构造读写锁

  //创建多个写线程
  for (i = 0; i < 2; i++){
    pthread_create(&tid[i], NULL, pth_write, (void *)i);
  }
    
  //创建多个读线程      
  for (i = 0; i < 4; i++){
    pthread_create(&tid[i+2], NULL, pth_read, (void *)i);
  }
   
  //等待子线程退出,回收其资源    
  for (i = 0; i < 6; i++){  
    pthread_join(tid[i], NULL);
  }   

  pthread_rwlock_destroy(&rwlock); //销毁读写锁
  return 0;
}	

多进程

最简

bash 复制代码
//app1.c	
#include <stdio.h>  //for printf
#include <unistd.h> //for sleep
int main(int argc,char **argv)
{
	while(1){
		printf("app1 go\n");
		sleep(5);
	}	
	return 0;
}		

//app2.c	
#include <stdio.h>
#include <unistd.h> 
int main(int argc,char **argv)
{
	while(1){
		printf("app2 go\n");
		sleep(5);
	}	
	return 0;
}		

$ gcc app1.c -o app1
$ gcc app2.c -o app2
$ ./app1 & //后台运行程序app1
$ ./app2 & /*后台运行程序app2
可成功看到 两个程序 在并发执行
app1 go
app2 go
app1 go
app2 go
app1 go

*/
$ ps -a /*查看所有的运行进程 
240442 pts/0    00:00:00 app2
240445 pts/0    00:00:00 app1
240447 pts/0    00:00:00 ps
*/
$ kill -9  240442 //杀死进程
$ kill -9  240445 

创建进程的副本

bash 复制代码
fork  //创建副本分支(子进程)去完成新任务,而父进程继续跑

对多任务不友好 //fork 是早期unix 为了让 shell能执行别的东西,
        //一种是执行完后回来接着做即fork,一种是直接替换老的(用exec),
        //那是还没有多任务概念,所有可读性封装都不好, pthread比它先进,用得更多
       
扩展了解 //vfork: 子进程共享 父进程地址空间,类似线程  -> 用的少 ,很多场景用线程即可
         //clone:有选择性的继承父进程的资源
         //exec: 替换父进程,进程ID不变 

//main.c	
#include <stdio.h>
#include <unistd.h>

int main(int argc,char **argv)
{
	printf("Progress start pid =%d\n",getpid());
	pid_t id=fork(); //复制创建新的进程分叉(子进程)
	    //fork后,父子进程谁先执行 由内核调度器决定	
	   //写时复制(惰性复制):数据段代码段共享,只有修改数据时,才拷贝数据段的数据 -> 独立,节省开销        
	if(id<0){ //返回值为负表示失败
		printf("fork err\n");
		return -1;
	}
	else if(id=0){ //fork后,子进程返回值为0  
		//fork出子进程 去做新的事情。   而父进程继续做原来的事情
		printf(" son progress  pid = %d do new work\n",getpid());	    	
	}else{   //父进程返回值>0
		printf(" progress go  pid = %d \n",getpid());	   	
	}

	sleep(1);
	return 0;
}	

//验证测试
$ gcc main.c
$./a.out /*
Progress start pid =239876
pid = 239876 go
father progress go  pid = 239876 
pid = 239877 go  复制创建的新进程(子进程)
son progress pid = 239877  do new work 
*/

进程并发控制

进程是独立地址空间 //进程间无需互斥,

访问设备,设备被占用 //可用内核里互斥机制去解决(同步是以互斥为基础的)

进程间更多是同步问题 //如访问设备时,设备忙你如何去处理,

//多个设备或资源,被多个进程用,它们关系如何协调(等待队列)

//后面会讲到阻塞非阻塞异步通知

总结

并发系统;如何性能进行优化

无锁化,性能最大化

并发多个任务的时,就有争抢的问题;

进程进程、进程中断、cpu之间

原子操作:最小的不可分割

中断屏蔽:关中断;屏蔽断,会中断滞后;不能睡眠

自旋锁:cpu忙等待;没限制,不会睡眠,得到读写锁、顺序锁

锁:都不会睡眠

读写锁:读多

顺序锁:写多,重读

RCU:读写锁优化;写时拷贝:写到另外空间

互斥体:会睡眠

信号量:多个资源,资源的技术、同步场景

应用态:

线程里:自旋锁、读写锁;互斥体、信号量

线程尽量的小

进程尽量的独立

相关推荐
黑十7 分钟前
FDE 怎么快速搭一个可演示页面?最小前端方案
java·大数据·前端·数据库·人工智能
Funlang9 分钟前
在 Windows 95 上写前端
前端·javascript·windows
cidy_9827 分钟前
python第7课. 输入与输出
前端
神明不懂浪漫28 分钟前
【第八章】多线程(一)
java·开发语言·经验分享·笔记
小龙666632 分钟前
给 Agent 一张地图,而不是一座迷宫:前端 monorepo 目录结构重构实录
前端·agent
樊小肆34 分钟前
agent 不报错才最吓人:自研编码工具半年,我踩了 10 个"看着正常"的运行时坑
前端·人工智能·agent
鲸鹏芯海微电子科技上海有限公司39 分钟前
手机直连卫星,射频前端到底要解决什么?
前端·后端
FungLeo40 分钟前
FengCMS · PHP+MySQL 升级实录 · Web 入口收敛:Apache/Nginx 白名单挡住配置、安装 SQL、上传脚本直连
前端·mysql·php·安全加固·fengcms
费曼学习法1 小时前
12 个工具调用改成并发,耗时从 94 秒掉到 23 秒:DeepSeek 并行调用工程细节
前端