This is the context:
I need to run a method n times one after the other (not at the same time) and n can be incremented by multiple threads. I want to limit this to 255 times (condition) so I have next code:
public class MyClass
{
int number = 0;
public void Caller()
{
Thread thread = new Thread(new ThreadStart(Request));
thread.Start();
Thread thread2 = new Thread(new ThreadStart(Request));
thread2.Start();
Thread thread3 = new Thread(new ThreadStart(Request));
thread3.Start();
}
public void Request()
{
// Condition
if (number < 255)
{
// Queue a new method
System.Threading.Interlocked.Increment(ref number);
}
// If it is the first time that Request is called, then it starts to run Method "number" times
if (number == 1)
StartRunnigMethods();
}
public void StartRunningMethods()
{
while (number > 0)
{
Method();
System.Threading.Interlocked.Decrement(ref number);
}
}
public void Method()
{
...
}
}
Due to the multithreading nature, I'm concerned about the Request method when I modify number if it is less than 255. So I implemented a solution but I'm not sure if it is a good implementation.
Modified code:
public void Request()
{
InterlockedIncrementIfLessThan(ref number, 255);
// It is the fisrt time Request is called
if( number == 1)
StartToRunTheMethod();
}
public bool InterlockedIncrementIfLessThan(ref int value, int condition)
{
int newValue, currentValue;
do
{
int initialValue = value;
currentValue = Thread.VolatileRead(ref value);
if (currentValue >= condition) return false;
newValue = initialValue + 1;
}
while (System.Threading.Interlocked.CompareExchange(ref value, newValue, initialValue) != initialValue);
return true;
}
What would be the best way to perform a comparison (less than) and if it is true then increment the variable (number)?
I'm new on these topics so may be you could recommend me good references to start with.