读者写者问题(读者优先,写者优先 ,读写公平)

读者优先

读者优先的解决方案:

互斥信号量wrt,初值是1,代表一个共享文件,解决“读-写”互斥,“写-写”互斥。

一个记数器,即整型变量readcount,记录读者数,初值是0。 来一个读者, readcount加1 当readcount =1表示是第一个读者, 则需要执行p操作抢占文件;否则表示已有读者在安全的读数据。 走一个读者,readcount减1 当readcount =0表示是最后一个读者,则需要v操作释放资源;否则表示还有读者在读数据。

readcount 为多个读者共享的变量,是临界资源。用互斥信号量mutex控制, mutex初值是1。

代码:

int readcount=0; 
semaphore mutex=1, wrt=1 ; 

读者进程:
        wait (mutex);
	readcount++;	
	if (readcount == 1)
	       wait(wrt);
	signal (mutex);
		…
	   reading is performed
		 …
	wait (mutex);
	readcount--;
	if (readcount == 0)
		signal (wrt);
	signal (mutex);


写者进程:     
      wait(wrt);
	    …
         writing is performed
	    …
      signal(wrt);

写者优先

解决方案:

在读者优先的基础上

增加信号量r,初值是1:当至少有一个写进程准备访问数据区时,用于禁止所有的读进程。

增加一个记数器,即整型变量writecount,记录写者数,初值是0。 writecount为多个写者共享的变量,是临界资源。用互斥信号量mutex2控制, mutex2初值是1。

增加mutex3,初值是1:在r上不允许建造长队列,否则写进程将不能跳过这个队列,因此,只允许一个读进程在r上排队,而所有其他读进程在等待r之前,在信号量mutex3上排队。

代码:

int readcount=0, writecount=0; 
semaphore mutex1=1, mutex2=1, mutex3=1, w=1, r=1 ; 

读者进程:
P(mutex 3);
   P(r);
      P(mutex 1);
         readcount++;
         if (readcount == 1 ) 
            P(w);
      V(mutex 1);
    V(r);
V(mutex 3);
      reading is performed
P(mutex 1);
    readcount --;
    if (readcount == 0 )
             V(w);
V(mutex 1);

写者进程:     
P(mutex 2);
    writecount++;
    if (writecount == 1 )
           P(r);
V(mutex 2);
P(w);
    writing is performed
V(w);
P(mutex 2);
    writecount --;
    if (writecount == 0)
           V(r);
V(mutex 2); 

读写公平

 

代码:

int readcount=0; 
semaphore mutex=1, rw=1 w=1; 

读者进程:
        wait (w);
        wait (mutex);
        if (readcount == 0)
	       wait(rw);
    	readcount++;	
    	signal (mutex);
        signal (w);
		…
    	   reading is performed
		 …
    	wait (mutex);
    	readcount--;
    	if (readcount == 0)
    		signal (rw);
    	signal (mutex);


写者进程:     
    wait(w);
    wait(rw);
	    …
         writing is performed
	    …
    signal(rw);
    signal(w);

 

你可能感兴趣的:(操作系统)