public Reader(ConcurrentBag <string> receivedMessages, ManualResetEventSlim readWaitHandle,
               ManualResetEventSlim writeWaitHandle, object padlock, SharedDataContainer container)
 {
     _receivedMessages = receivedMessages;
     _writeWaitHandle  = writeWaitHandle;
     _readWaitHandle   = readWaitHandle;
     _padlock          = padlock;
     _container        = container;
 }
Example #2
0
 public Writer(int id, int numberOfMessages, ManualResetEventSlim readWaitHandle,
               ManualResetEventSlim writeWaitHandle, object padlock, SharedDataContainer container)
 {
     _id = id;
     _numberOfMessages = numberOfMessages;
     _writeWaitHandle  = writeWaitHandle;
     _readWaitHandle   = readWaitHandle;
     _padlock          = padlock;
     _container        = container;
 }
Example #3
0
        public ConcurrentBag <string> Process()
        {
            var container        = new SharedDataContainer();
            var padlock          = new object();
            var receivedMessages = new ConcurrentBag <string>();
            var readWaitHandle   = new ManualResetEventSlim(true);
            var writeWaitHandle  = new ManualResetEventSlim(false);
            var readers          = new Thread[NumberOfReaders];

            for (int i = 0; i < NumberOfWriters; i++)
            {
                int id     = i;
                var writer = new Writer(id, NumberOfMessages, readWaitHandle, writeWaitHandle, padlock, container);
                var thread = new Thread(() => writer.Write())
                {
                    Name = "Writer" + id, Priority = Priority
                };
                thread.Start();
            }

            for (int i = 0; i < NumberOfReaders; i++)
            {
                var reader = new Reader(receivedMessages, readWaitHandle, writeWaitHandle, padlock, container);
                var thread = new Thread(() => reader.Read())
                {
                    IsBackground = true,
                    Name         = "Reader" + i,
                    Priority     = Priority
                };
                readers[i] = thread;
                thread.Start();
            }

            var totalMessages = NumberOfMessages * NumberOfWriters;

            while (container.WritersFinished < NumberOfWriters || receivedMessages.Count < totalMessages)
            {
                Thread.Sleep(1);
            }

            container.IsCancelled = true;

            for (int i = 0; i < NumberOfReaders; i++)
            {
                readers[i].Interrupt();
            }

            return(receivedMessages);
        }