管程理解及用管程实现生产者消费者问题

2.17 管程

管程是一个程序设计语言结构,采用了集中式的进程同步方法,提供了与信号量同样的功能,但更易于控制

概念

由一个共享数据结构(资源的抽象)和为并发进程执行的一组操作组成,这组操作可同步进程和改变管程中的数据

特点
  1. 局部变量只能被管程内的过程访问
  2. 进程通过调用管程的一个过程进入管程
  3. 无论何时仅有一个进程在管程中执行,仅当该进程结束或阻塞时管程才可供其他进程调用(非抢占)
    在这里插入图片描述
管程实现的互斥是一种依靠数据结构的互斥,管程相当于一个互斥函数
管程实现同步

使用条件变量(局部变量)
操作条件变量的两个函数:

  • cwait©:进程在c上阻塞,此时管程可共其他进程调用
  • csignal©:恢复在c上阻塞的一个进程
管程解决生产者消费者问题
/* program producerconsumer * /

monitor boundedbuffer;
char buffer [N];            /*space for N items */
int nextin,nextout;         /*buffer pointers */
int count;					/* number of items in buffer */
cond notfull,notempty;		/*condition variables for synchronization */

//定义append()
void append (char x){
    
    
	if (count == N) cwait ( notfull);	/*buffer is full; avoid overflow * /
	buffer[nextin] = x;
	nextin = (nextin + 1) % N;
	count++;
	/*one more item in buffer */
	csignal(notempty);					/*resume any waiting consumer * /
}

//定义take()
void take (char x){
	if (count == 0 ) cwait(notempty);	/* buffer is empty; avoid underflow */
	x = buffer[ nextout];
	nextout = ( nextout + 1)% N;
	count--;							/*one fewer item in buffer */
	csignal (notfull);					/*resume any waiting producer * /
}

{										/* monitor body */
	
	nextin = 0; nextout = 0; count = 0; /* buffer initially empty */
}

void producer()
{
    
    
    char x;
    while (true)  {
    
    
        produce(x); 
        append(x);    
  }
}

void consumer
{
    
    
    char x;
    while (true) {
    
    
        take(x);
        consume(x);     
    }
}

void main
{
    
    
    parbegin (producer,    
    consumer) ;
}


在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44722674/article/details/111570161