ALL > Computer and Education > courses > university courses > undergraduate courses > Operating System > ZSTU-(2020-2021)-1 > student homework > >
homework6 Version 0
👤 Author: by 653968106qqcom 2020-11-04 05:17:56

Use semaphore to solve reader writer problem(writer first)


Through semaphore mechanism and corresponding system call, it is used for mutual exclusion and synchronization of threads to realize reader writer problem. Using semaphore mechanism, the reader writer problem is realized.

In Windows 10 environment, create a console process, which contains n threads. Use these n threads to represent n readers or writers. Each thread reads and writes according to the settings. The semaphore mechanism is used to implement reader first and writer first reader writer problems respectively.

Writer first:

There are similarities between writer first and reader first. The difference is: once a writer arrives, the writer should be allowed to write as soon as possible. If a writer is waiting, the new reader operation cannot read. Therefore, an integer variable, writercount, is added to record the number of writers. When writercount = 0, readers can be released for reading.

In order to realize mutual exclusive access to the global variable writercount, a mutex semaphore WC is set_ At the same time, if the reader thread wants to implement the operation mutual exclusion of the global variable readercount, there must be a mutex object named.

In order to achieve writer first, a critical section object read is set up. When a writer is writing or waiting, the reader must block the critical section object read. Similarly, when a reader is reading, the writer must wait. Therefore, there must be a mutex object book to implement the mutex.

If the writer's operation should take precedence over the reader's, the semaphore will be occupied until there is no writer. That is, when the writercount is equal to 1, the semaphore book is applied for, and the rest of the writers do not need to apply again, but the writer can not write at the same time, so a semaphore wrt needs to be set to ensure that only one writer writes at a time When the number of writecount is equal to 0, it proves that there are no readers at this time, and the semaphore book is released. When readcount is 1, in order to prevent the writer from writing, if the semaphore wrt is applied, the writer cannot write. The main use of the semaphore mutex is to avoid the writer competing with multiple readers at the same time. The semaphore book is released earlier than mutex, so once there is a writer, the writer can get the resources immediately.

code





result

Please login to reply. Login

Reversion History

Loading...
No reversions found.