I have multiple producers and multiple consumers. My shared resource is the BlockingCollection. However, my code only works if I have one consumer. I know it is a race condition since the output is different each time I run the code.
I thought BlockingCollection would take care of all the syncing etc. but it does not.
How can I sync my shared resource among all the producers and consumers then?
Here is my code:
/// <summary>
/// PURE PRODUCER TYPE
/// </summary>
class Caller
{
private BlockingCollection<Call> incommingCalls;
public Caller(BlockingCollection<Call> calls)
{
incommingCalls = calls;
//start the producer thread
Thread thread = new Thread(new ThreadStart(placeCall));
thread.Start();
}
public void placeCall()
{
incommingCalls.Add(myCall);
}
}
/// <summary>
/// CONSUMER
/// </summary>
class Fresher : Employee
{
private BlockingCollection<Call> calls;
public Fresher(BlockingCollection<Call> incalls)
{
calls = incalls;
Thread thread = new Thread(new ThreadStart(HandleCalls));
thread.Start();
}
/// <summary>
///
/// </summary>
public void HandleCalls()
{
while (!incommingCalls.IsCompleted)
{
Call item;
if (incommingCalls.TryTake(out item, 100000))
{
//do something with the call
} //else do nothing - just wait
}
}
/// <summary>
///
/// </summary>
class CallCenter
{
private BlockingCollection<Call> fresherCalls;
private List<Caller> myCallers;
private List<Employee> myFreshers;
public CallCenter()
{
//initial incomming calls to the fresher queue
fresherCalls = new BlockingCollection<Call>();
myFreshers = new List<Employee>();
myCallers = new List<Caller>();
generate_freshers();
//generate to start the producer
generate_callers();
}
/// <summary>
///
/// </summary>
private void generate_freshers()
{
for (int i = 0; i < 1; i++ )
{
myFreshers.Add(new Fresher(fresherCalls, tlCalls, locker2));
}
}
/// <summary>
///
/// </summary>
private void generate_callers()
{
for (int i = 0; i < 20; i++ )
{
myCallers.Add(new Caller(fresherCalls, locker));
}
}
}
BlockingCollection<T>
like that... In general, specific ordering tends to dramatically reduce or eliminate the gains you get by concurrent programming. Problems that scale well in concurrent space tend to be ones where order of processing doesn't matter. – Reed Copsey