Is this code lack proper synchronization because I use Set()
and immediately Reset()
?
using System.Threading;
class Shared
{
public static int[] Data { get; set; } // Stores data values generated by producer thread
public static int BatchCount { get; set; } // Total number of values
public static int BatchSize { get; set; }
public static ManualResetEvent Event { get; set; }
static Shared()
{
Data = new int[15];
BatchCount = 5;
BatchSize = 3;
Event = new ManualResetEvent(false); // unsignaled (false)
}
}
// Represents producer thread
class Producer
{
public void Produce()
{
Console.WriteLine($"{Thread.CurrentThread.Name} started");
for (int i = 0; i < Shared.BatchCount; i++)
{
// Generate some data and store it in the Data array
for (int j = 0; j < Shared.BatchSize; j++)
{
Shared.Data[i * Shared.BatchSize + j] = (i * Shared.BatchSize) + j + 1;
Thread.Sleep(300); // Simulate artificial latency (delay)
}
// Set the signal (signal that the producer has finished generating data)
Shared.Event.Set();
// Reset the signal (makes the consumer thread wait for signal before reading next batch)
Shared.Event.Reset();
}
Console.WriteLine($"{Thread.CurrentThread.Name} Completed");
}
}
// Represents consumer thread
class Consumer
{
public void Consume()
{
Console.WriteLine($"{Thread.CurrentThread.Name} started");
Console.WriteLine("Consumer is waiting for producer thread to finish generating data");
for (int i = 0; i < Shared.BatchCount; i++)
{
Shared.Event.WaitOne(); // consumer thread waits until the status of event becomes singaled
Console.WriteLine("Consumer has received a signal from the Producer");
// Read data
Console.WriteLine("n Data is");
for (int j = 0; j < Shared.BatchSize; j++)
{
Console.WriteLine(Shared.Data[i * Shared.BatchSize + j]);
}
}
Console.WriteLine($"{Thread.CurrentThread.Name} Completed");
}
}
class Program2
{
static void Main()
{
// Create objects of Producer and Consumer class
Producer producer = new Producer();
Consumer consumer = new Consumer();
// Create delegate objects of ThreadStart
ThreadStart threadStart1 = new ThreadStart(producer.Produce);
ThreadStart threadStart2 = new ThreadStart(consumer.Consume);
// Create thread objects
Thread producerThread = new Thread(threadStart1) { Name = "Producer Thread" };
Thread consumerThread = new Thread(threadStart2) { Name = "Consumer Thread" };
// Start Threads
producerThread.Start();
consumerThread.Start();
// Join both threads to the main threads
producerThread.Join();
consumerThread.Join();
Console.WriteLine("End of main method");
}
}