I asked this question before - but for some time I thought about it and implemented a working version.
Overview
1) Threads are created to perform a specific task.
2) Only one thread can perform a task at a time.
3) Each thread performs the same task. (Has a bunch of checks and validations in the system)
3) Threads are created faster than the task can be completed. (I do not control the creation of the thread)
The result is that overtime I get lagged behind threads to complete the task.
I implemented the following: 1) Thread checks how many active threads are.
2) If there are 0 threads, it is marked as PerformTask, and it starts the task
3) If there is 1 thread, it is marked PerformTak, and it blocks 4) If there are more than 1 thread, the thread is not marked for PerformTasks and just dies
The idea is that if there is a thread waiting to complete a task, I just kill the thread.
Here is the code I came up with
bool tvPerformTask = false;
ivNumberOfProcessesSemaphore.WaitOne();
if (ivNumberOfProcessesWaiting == 0 ||
ivNumberOfProcessesWaiting == 1)
{
ivNumberOfProcessesWaiting++;
tvPerformTask = true;
}
ivNumberOfProcessesSemaphore.Release();
if (tvPerformTask)
{
ivProcessSemaphore.WaitOne();
ivProcessSemaphore.Release();
ivNumberOfProcessesSemaphore.WaitOne();
ivNumberOfProcessesWaiting--;
ivNumberOfProcessesSemaphore.Release();
}
else
{
}
The problem that I have is not that it does not work, simply because I do not find the code elegant, especially I am not very pleased that I need 2 integer semaphores and a local flag to manage all this. If there is a way to implement this or a template that will make the code simpler.
source
share