IPC.读者-写者问题

A问题:

  Courtois et al于1971年提出。

  可以多读取,但是写入时不允许读取、写入。

A解决:

 1 typedef int semaphore;
 2 semaphore mutex = 1;
 3 semaphore db = 1;
 4 int rc = 0;
 5 void reader(void)
 6 {
 7     while(TRUE)
 8     {
 9          down(&mutex);
10          rc += 1;
11          if(rc == 1)down(&db);
12          up(&mutex);
13          read_date();
14          down(&mutex);
15          rc -= 1;
16          if(rc == 0)up(&db);
17          up(&mutex);
18     }
19 }
20 void writer(void)
21 {
22     while(TRUE)
23     {
24         think_up_data();
25         down(&mutex);
26         write_data();
27         up(&mutex);
28     }
29 }

临界区变量互斥操作

读:

第一次访问数据库信号量down

访问全部退出数据库信号量up

写:

只有信号量可down才写

 

自第一次访问,数据库信号量就一直不可再down,所以写不了,必须全读完才可写(读者优先)

posted @ 2018-04-21 16:14  扑克face  阅读(179)  评论(0编辑  收藏  举报