Reader-Writer Synchronization Technology Sample

This sample demonstrates use of the ReaderWriterLock thread synchronization class. The functionality of the ReaderWriterLock type allows the developer to write code that enforces exclusive access to a shared resource while a thread is writing or modifying the resource, but allows non-exclusive access when reading or querying the resource.

For more information about using the samples, see the following topics:

To build the sample using the command prompt

  1. Open a Command Prompt window and navigate to one of the language-specific subdirectories for the sample.

  2. Type msbuild ReaderWriterSynchronizationCS.sln or msbuild ReaderWriterSynchronizationVB.sln, depending on your choice of programming language, at the command line.

To build the sample using Visual Studio

  1. Open Windows Explorer and navigate to one of the language-specific subdirectories for the sample.

  2. Double-click the icon for ReaderWriterSynchronizationCS.sln or ReaderWriterSynchronizationVB.sln, depending on your choice of programming language, to open the file in Visual Studio.

  3. On the Build menu, click Build Solution.

To run the sample

  1. Navigate to the directory that contains the new executable file.

  2. Type ReaderWriter.exe from the command line.

    NoteNote

    This sample builds a console application. You must launch it from the command prompt in order to view its output. When running the sample, notice that the Start Writing and Stop Writing output for each writer occurs successively. This is because the writers hold exclusive access to the resource, unlike the readers.

Remarks

For more information about thread synchronization and exclusive access, see the comments in the source code and build.proj files.

The following bullets briefly describe the classes and technologies used by this sample.

  • Thread Synchronization

ReaderWriterLock Used to protect a logical resource which is implemented as a call to Sleep. Threads using the ReaderWriterLock type can hold the lock in two different ways. First, a thread can hold a read-lock, which is non-exclusive and will allow other threads to gain a read-lock for the class. Second, a thread can request a write-lock, which is exclusive, and is not granted until currently held read and write locks are released.

  • Threading

    • ThreadPool When writing managed code, it is suggested that whenever possible, developers use the QueueUserWorkItem method to implement asynchronous method calls. This sample uses this approach to execute code that contends for a logical resource.
  • Delegates

    • WaitCallback Used to create a type-safe callback method for the ThreadPool class to use.

See Also

Reference

AutoResetEvent
Delegate
Interlocked
Mutex
System.Threading
ThreadPool
WaitCallback
WaitHandle

Concepts

Threads and Threading

Other Resources

Threading Objects and Features