2018329621184_边凯昂_homework5 Version 0 |
|
👤 Author: by 244766935qqcom 2020-11-06 13:27:41 |
# Problem Descr iption:
A database could be shared by multithreads. Some threads are used for only reading while others are functioning upgrasion. The former user is called reader and the later is called the writer. If writing and other users(neither writer nor reader) concurrently share the object, it might be confused. At these time, to ensure the such kind of hard cases happen, writers are required to exclude the other who access the shared databases.
# Solutions:
## Basic
To overcome this difficulty, we employ a synchronization tool called semaphore.
We define a semaphore as follow:
typedef struct {
int value;
struct process *list;
} semaphore;
semaphore mutex, wrt;
int readcount;
The semaphores mutex and wrt are initialized to 1; readcount is initialized to 0. The semaphore wrt is common to both reader and writer processes. The mutex semaphore is used to ensure mutual exclusion when the variable readcount is updated. The readcount variable keeps track of how many processes are currently reading the object. The semaphore wrt functions as a mutual-exclusion semaphore for the writers. It is also used by the first or last.
## Specific
For waiting(starving) writers, I render the following code to solve the problem
do {
wait(wrt);
// Writing is performed
signal(wrt);
} while(TRUE);
For reader:
do {
wait(mutex);
readcount++;
if (readcount==1)
wait(wrt);
signal(mutex);
// reading is performed
wait(mutex);
readcount--;
if (readcount == 0)
signal(wrt);
signal(mutex);
} while(TRUE);