G
Guest
I am developing an application that has several multi threaded tasks where
one thread is doing IO and another thread is grabbing data from the first
thread to process it further.
I've been noticing that every once in a while my program simply hangs- it is
rare but it is annoying. I am worried it may be a synchronization issue
involving my producer/consumer threads.
I basically go like this:
So the basic idea here is my producer makes token objects which get pushed
onto a Queue using the AddToken method. If the queue was empty, it sets the
AutoResetEvent so any waiting consumer thread is awakened.
A consumer thread would either call HasMoreTokens or NextToken which will
wait if the status is not 'DONE' (aka the producer is still working) and
the queue is empty. Once a token on the queue is available, it will get
awoken by the producer.
Does this look flawed?
one thread is doing IO and another thread is grabbing data from the first
thread to process it further.
I've been noticing that every once in a while my program simply hangs- it is
rare but it is annoying. I am worried it may be a synchronization issue
involving my producer/consumer threads.
I basically go like this:
Code:
AutoResetEvent autoEvent = new AutoResetEvent(false);
Queue q = new Queue();
private void AddToken (Token t)
{
lock (q)
{
q.Enqueue(t);
if (q.Count == 1) { autoEvent.Set(); }
}
}
public bool HasMoreTokens ()
{
if (status < StatusType.DONE && q.Count == 0)
{
autoEvent.WaitOne(); autoEvent.Reset();
}
return (q.Count > 0);
}
public Token NextToken ()
{
while (status < StatusType.DONE && q.Count == 0)
{
autoEvent.WaitOne(); autoEvent.Reset();
}
lock (q)
{
return (Token)q.Dequeue();
}
}
So the basic idea here is my producer makes token objects which get pushed
onto a Queue using the AddToken method. If the queue was empty, it sets the
AutoResetEvent so any waiting consumer thread is awakened.
A consumer thread would either call HasMoreTokens or NextToken which will
wait if the status is not 'DONE' (aka the producer is still working) and
the queue is empty. Once a token on the queue is available, it will get
awoken by the producer.
Does this look flawed?