C
Cool Guy
The main thread of my application will add items to a queue, which another
thread will dequeue items from. This other thread will then perform a
blocking operation with each item it finds.
Is it possible to do this in a thread-safe manner?
I imagine something like this would work:
// ran in background thread
void DequeuerThreadMethod()
{
while (!Finished)
{
object item;
lock (queue)
{
item = queue.Dequeue();
}
DoBlockingOperation(item);
lock (queue)
{
if (queue.Count == 0)
SuspendThisThread();
}
}
}
// ran in main application thread
void AddToQueue(object item)
{
lock (queue)
{
queue.Enqueue(item);
}
ResumeDequeuerThread();
}
Will this be thread-safe?
thread will dequeue items from. This other thread will then perform a
blocking operation with each item it finds.
Is it possible to do this in a thread-safe manner?
I imagine something like this would work:
// ran in background thread
void DequeuerThreadMethod()
{
while (!Finished)
{
object item;
lock (queue)
{
item = queue.Dequeue();
}
DoBlockingOperation(item);
lock (queue)
{
if (queue.Count == 0)
SuspendThisThread();
}
}
}
// ran in main application thread
void AddToQueue(object item)
{
lock (queue)
{
queue.Enqueue(item);
}
ResumeDequeuerThread();
}
Will this be thread-safe?