Skip to content

Instantly share code, notes, and snippets.

@NonymousMorlock
Last active January 17, 2023 12:24
Show Gist options
  • Save NonymousMorlock/04eb6e7308a83d321bb2803ff0cf72a0 to your computer and use it in GitHub Desktop.
Save NonymousMorlock/04eb6e7308a83d321bb2803ff0cf72a0 to your computer and use it in GitHub Desktop.

C++

Here are the outcomes under the different scenarios:

  • If a reader comes first, it will be able to read the data in the database.
  • If a reader is using the database and another reader comes along, the second reader will also be able to read the data in the database.
  • If a writer comes along while a reader is active, the writer will wait until the reader is finished before it can write to the database. If a supply of readers arrives after the writer, they will also have to wait until the writer is finished before they can read the data in the database.
  • If a reader arrives and a writer is waiting, the writer will have to wait until the reader is finished before it can write to the database.

This program creates 10 reader threads and 2 writer threads. The reader threads continually read the value of the database variable, while the writer threads continually update it. The ReaderWriterLockSlim class is used to synchronize access to the database variable. When a writer thread acquires a write lock, it is able to update the database variable, but no other threads (either readers or writers) can access the variable until the write lock is released. Similarly, when a reader thread acquires a read lock, it is able to read the database variable, but no other threads can write to the variable until all the read locks are released.

C#

Here is what would happen under the following different scenarios:

  • If a reader comes first, it will be able to acquire a read lock and read the value of the database variable.
  • If a reader is using the database and another reader comes along, the second reader will be able to acquire a read lock and read the value of the database variable. Multiple readers can acquire read locks simultaneously, so multiple readers can access the database variable at the same time.
  • If a writer comes along while a reader is active, the writer will have to wait until all the read locks are released before it can acquire a write lock and update the database variable.
  • If a reader arrives and a writer is waiting, the reader will be able to acquire a read lock and read the value of the database variable. The writer will have to wait until all the read locks are released before it can acquire a write lock and update the database variable.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment