Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading;
- namespace ParallelWork;
- class Program
- {
- static readonly object locker = new();
- static int sharedData;
- static int readerCount;
- static bool writerActive;
- static void Main()
- {
- for (var i = 0; i < 3; i++)
- {
- var readerThread = new Thread(Reader);
- readerThread.Start();
- }
- for (var i = 0; i < 2; i++)
- {
- var writerThread = new Thread(Writer);
- writerThread.Start();
- }
- }
- private static void Reader()
- {
- while (true)
- {
- lock (locker)
- {
- if (writerActive) Monitor.Wait(locker);
- readerCount++;
- Thread.Sleep(2000);
- Console.WriteLine("ReaderThread {0} считал данные: {1}", Thread.CurrentThread.ManagedThreadId, sharedData);
- readerCount--;
- Monitor.PulseAll(locker);
- }
- }
- }
- private static void Writer()
- {
- while (true)
- {
- lock (locker)
- {
- if (writerActive || readerCount > 0)
- Monitor.Wait(locker);
- writerActive = true;
- sharedData++;
- Thread.Sleep(1000);
- Console.WriteLine("WriterThread {0} записал данные: {1}", Thread.CurrentThread.ManagedThreadId, sharedData);
- writerActive = false;
- Monitor.PulseAll(locker);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement