首页 > 其他分享 >《信息安全与设计》第四章学习笔记

《信息安全与设计》第四章学习笔记

时间:2022-10-14 00:33:47浏览次数:49  
标签:attr int void 信息安全 笔记 互斥 线程 pthread 第四章

第4章 并发编程

知识点归纳

并行性和并发性
1.真正的并行执行只能在多个处理组件的系统中实现,比如多处理器或多核系统。
2.在单CPU系统中,并发性是通过多任务处理实现的。

线程
1.线程的原理
(1)在内核模式下,各进程在唯一地址空间上执行,与其他进程是分开的;
(2)每个进程都是一个独立单元,只有一个执行路径;
(3)线程是某进程同一地址空间上的独立执行单元,如果只有一个主线程,那么进程和线程并没有什么本质区别。
2.线程的优点
(1)线程创建和切换速度更快。
(2)线程的响应速度更快。
(3)线程更适合并行计算
3.线程的缺点
(1)由于地址空间共享,线程需要来自用户的明确同步。
(2)许多库函数可能对线程不安全。
(3)在单CPU系统上,使用线程解决间题实际上要比使用顺序程序慢,这是由在运行时创建线程和切换上下文的系统开销造成的。
4.线程操作
(1)线程可在内核模式或用户模式下执行。
(2)在用户模式下,线程在进程的相同地址空间中执行,但每个线程都有自己的执行堆栈。
(3)线程是独立的执行单元,可根据操作系统内核的调度策略,对内核进行系统调用,变为桂起激活以继续执行等。
(4)为了利用线程的共享地址空间,操作系统内核的调度策略可能会优先选择同一进程中的线程,而不是不同进程中的线程。
(5)线程管理函数
A.Pthread库提供了用于线程管理的以下API

pthread_create(thread, attr, function, arg): create thread
pthread_exit(status):terminate thread
pthread_cancel(thread) : cancel thread
pthread_attr_init(attr) : initialize thread attributes
pthread_attr_destroy(attr): destroy thread attribute

B.创建线程
使用pthread_create()函数创建线程。

int pthread_create (pthread_t *pthread_id,pthread_attr_t *attr,
void * (*func) (void *), void *arg);

其中,attr最复杂,其使用步骤为
a.定义一个pthread属性变址pt:hread_attr_tattr;
b.用pthread_attr_init(&attr)初始化屈性变掀;
c.设置属性变垃并在pthread_create()调用中使用;
d.必要时,通过pthread_attr_destroy(&attr)释放attr资源.
C.线程终止
线程函数结束后,线程即终止,或者,线程可以调用函数int pthraad_exit {void *status)进行显式终止,其中状态是线程的退出状态。
D.线程连接
一个线程可以等待另一个线程的终止, 通过:
int pthread_join (pthread_t thread, void **status__ptr);
终止线程的退出状态以status_ptr返回。

线程同步
当多个线程试图修改同一共享变量或数据结构时,如果修改结果取决于线程的执行顺序,则称之为竞态条件。

1.互斥量
(1)在 Pthread中,锁被称为互斥量,意思是相互排斥。

(2)互斥变呈是用 ptbread_mutex_t类型声明的在使,用之前必须对它们进行初始化。有两种方法可以初始化互斥址:
A.静态方法:pthreaa—mutex_t m = PTHREAD_MUTEX_INITIALIZER,定义互斥量 m, 并使用默认属性对其进行初始化。
B.动态方法,使用 pthread_ mutex _init() 函数

(3)线程通过互斥量来保护共享数据对象

2.死锁预防
死锁是一种状态,在这种状态下,许多执行实体相互等待,因此都无法继续下去。
死锁预防,试图在设计并行算法时防止死锁的发生。
一种简单的死锁预防方法是对互斥量进行排序,并确保每个线程只在一个方向请求互斥量,这样请求序列中就不会有循环。

3.条件变量
条件变量提供了一种线程协作的方法。
在Pthread中,使用类型pthread_cond_t来声明条件变量,而且必须在使用前进行初始化。
与互斥变量一样,条件变量也可以通过两种方法进行初始化。
A.静态方法:pthread_cond_t con= PTHREAD_COND_INITIALIZER;定义一个条件变屾con,并使用默认属性对其进行初始化。
B.动态方法:使用pthread_cond_init()函数,可通过attr参数设置条件变量。为简便起见,我们总是使用NULLattr参数作为默认属性。

4.信号量
信号量是进程同步的一般机制。
信号量是一种数据结构:

struct sem{
  int value;
  struct process *queue
}s;

问题与解决

pthread_cancel()不能杀死线程

  #include <stdio.h>
  #include <stdlib.h>
  #include <unistd.h>
  #include <pthread.h>
  #include <string.h>
   
  void *func(void *arg){
      while(1);
      return NULL;
  }
  int main(){
      printf("main:pid=%d,tid=%lu\n",getpid(),pthread_self());
  
      pthread_t tid;
      int ret = pthread_create(&tid,NULL,func,NULL);
      if(ret != 0){
          fprintf(stderr,"pthread_create error:%s\n",strerror(ret));
          return 1;
      }
  
      ret = pthread_cancel(tid);
      if(ret != 0){
          fprintf(stderr,"pthread_cancel error:%s\n",strerror(ret));
          return 2;
      }
  
      pthread_exit((void*)0);
  
      return 0;
  }

原因:
使用pthread_cancel()终止线程,需要线程中存在取消点。
需要线程中有陷入内核的操作。
如果想要用pthread_cancel()终止一个没有陷入内核操作的线程,就需要手动添加取消点
在while循环中加入,pthread_testcancel()即可用pthread_cancel()杀死该线程,即循环改为:

 while(1) pthread_testcancel();
 return NULL;

实践

生产者-消费者问题

int data;//number of full buffers
pthread_mutex_t mutex;//mutex lock
pthread_cond_t empty,full;//condition variables
int init(){
	head = tail = data = 0;
	pthread_mutex_init(&mutex,NULL);
	pthread_cond_init(&full,NULL);
	pthread_cond_init(&empty,NULL);
}
void *producer (){
	int i;
	pthread_t me = pthread_self() ;
	for (i=0; i<N; i++){ //try to put N items into buf[ ]
		pthread_mutex_lock(&mutex);//lock mutex
		if(data == NBUF) {
			printf("producer %lu: all bufs FULL: wait\n",me);
			pthread_cond_wait(&empty, &mutex);//wait
		}
		buf[head++] = i+1;//item = 1,2?.,N
		head %=NBUF;//circular bufs
		data++;//inc data by 1
		printf("producer %lu: data=%d value=%d\n",me,data,i+1);
		pthread_mutex_unlock(&mutex);//unlock mutex
		pthread_cond_signal(&full);//unblock a consumer?if any
	}
	printf("producer %lu: exit \n",me);
}
void *consumer(){
	int i, c;
	pthread_t me = pthread_self();
	for(i=0; i<N; i++){
		pthread_mutex_lock(&mutex);//lock mutex
		if(data == 0){
			printf ("consumer %lu: all bufs EMPTY : wait\n",me);
			pthread_cond_wait(&full,&mutex);//wait
		}
    	c=buf[tail++];//get an item
		tail%=NBUF;
		data--;//dec data by 1
		printf("consumer %lu: value=%d\n",me,c);
		pthread_mutex_unlock(&mutex);//unlock mutex
		pthread_cond_signal(&empty);//unblock a producer,if any
	}
	printf("consumer %lu: exit\n",me);
}
int main(){
	pthread_t pro, con;
	init();
	printf("main: create producer and consumer threads \n");
	pthread_create(&pro,NULL, producer,NULL);
	pthread_create (&con,NULL,consumer,NULL);
	printf("main: join with threads\n");
	pthread_join(pro,NULL);
	pthread_join(con,NULL);
	printf("main: exit\n");
}

标签:attr,int,void,信息安全,笔记,互斥,线程,pthread,第四章
From: https://www.cnblogs.com/wxl2761407387/p/16790202.html

相关文章

  • C++学习笔记2
    类类与对象类和结构体的区别结构体相当于是只有类的数据域。但其区别有不仅仅如此。类除了数据域,还有函数域,即声明了方法,当然,一般其方法是在类外实现的。而结构体没有......
  • 《git学习笔记》
    git简介Linus花了两周时间自己用C语言写了一个分布式版本控制系统。安装gitLinux可以尝试输入git,看看系统有没有安装Git,如果没有安装,又碰巧用Debian或UbuntuLinux,通......
  • 自然科学之反物质-学习笔记
    大纲1.狄利克反粒子2.反物质发现3.应用一、狄拉克反粒子  1.1929年,狄拉克方程中提出反粒子公式(1)非相对运动:V人=V1+VA            ......
  • 代码笔记26 pytorch复现pointnet
    1浅浅记录一下model的复现,之后做好完整的工程放到github上2importtorch.nnasnnimporttorchimportnumpyasnpclasstnet(nn.Module):def__init__(self,......
  • Spring boot笔记4
    减少配置修改次数方便环境配置切换application.yml#默认加载的配置文件spring:profiles:active:prod application-dev.ymlapplication-prod.yml......
  • 计算机网络学习笔记
    计算机网络的概念相互分享资源的互联起来的自治计算机(computers)的集合自治(autonomous):非主从关系,对等的行为模式互联(interconnected):通信计算机(computers):数字化(数据,信......
  • Spring boot 笔记
    JSR303配置属性值的数据校验hibernate-validator        @Validated必须在主类上标注可以校验所有子类的所有属性@NotEmpty       ......
  • JavaScript高级程序设计笔记10 函数Function
    函数1.几种实例化函数对象的方式以函数声明的方式定义函数表达式箭头函数(arrowfunction)使用Function构造函数接收任意多个字符串参数,最后一个参数始终会被......
  • 深入理解css 笔记(4)
    处理元素高度的方式跟处理宽度不一样。之前对border-box的修改依然适用于高度。而且很有用,但是通常最好避免给元素指定明确的高度。当明确设置一个元素的高度时,内容可能......
  • Spring实战笔记二(bean的作用域、运行时注入、)
    一、bean的作用域      默认情况下,Spring应用上下文中所有bean都是以单例(singleton)的形式创建的。      Spring定义的多种作用域,可以基于这些作用域创建be......