第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");
}

原文地址:http://www.cnblogs.com/wxl2761407387/p/16790202.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性