How do I wait for all other threads to finish their tasks?
Posted
by
Mike
on Stack Overflow
See other posts from Stack Overflow
or by Mike
Published on 2010-12-24T07:44:18Z
Indexed on
2010/12/24
7:53 UTC
Read the original article
Hit count: 217
c#
|multithreading
I have several threads consuming tasks from a queue using something similar to the code below. The problem is that there is one type of task which cannot run while any other tasks are being processed.
Here is what I have:
while (true) // Threaded code
{
while (true)
{
lock(locker)
{
if (close_thread)
return;
task = GetNextTask(); // Get the next task from the queue
}
if (task != null)
break;
wh.WaitOne(); // Wait until a task is added to the queue
}
task.Run();
}
And this is kind of what I need:
while (true)
{
while (true)
{
lock(locker)
{
if (close_thread)
return;
if (disable_new_tasks)
{
task = null;
}
else
{
task = GetNextTask();
}
}
if (task != null)
break;
wh.WaitOne();
}
if(!task.IsThreadSafe())
{
// I would set this to false inside task.Run() at
// the end of the non-thread safe task
disable_new_tasks = true;
Wait_for_all_threads_to_finish_their_current_tasks();
}
task.Run();
}
The problem is I don't know how to achive this without creating a mess.
© Stack Overflow or respective owner