我有多个生产者和多个消费者。我的共享资源是 BlockingCollection。但是,我的代码只有在我有一个消费者时才有效。我知道这是一种竞争条件,因为每次运行代码时输出都不同。
我认为 BlockingCollection 会处理所有同步等,但事实并非如此。
那么如何在所有生产者和消费者之间同步我的共享资源呢?
这是我的代码:
/// <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));
}
}
}