Hi,
I thought, it is simple to explain my problem with the pseudo code.
This is how my code looks like.
public class A
{
private object locker = new object();
public bool pause = true;
private void M1()
{
while(true)
{
if(!pause)
CriticalMethod();
}
}
private void M2()
{
while(true)
{
if(!pause)
CriticalMethod();
}
}
private void M3()
{
while(true)
{
if(!pause)
CriticalMethod();
}
}
private void M4()
{
while(true)
{
if(!pause)
CriticalMethod();
}
}
private void CriticalMethod()
{
lock (locker)
{
pause=true;
}
}
}
Problem description:
There is a situation where 4 of my threads entered into
"CriticalMethod" method.Using
"lock", I can sync these threads but my requirement is not this.
My requirement is, when one of these threads first entered into this method, other threads even though entered into
"CriticalMethod" method later(after some fraction of ms or ns) they should exit(i.e they should not execute critical section again and again after lock frees the shared object).Here "lock" written to handle some other things(which am not disclosing here).
Using "pause" variable, somehow I am able to make other threads skip entering
"CriticalMethod" method but I know that it is not appropriate way.This trick works sometimes but not always.
So please share me the pseudo code how this situation can be handled.I referred many urls on this.Some of them suggested using of Semaphore,Monitor.TryEnter(object), Interlocked class.
Please suggest me which is efficient among them or any other way to do handle this.Simple, clean pseudo code helps me.Because in many urls it was difficult to me understand(especially Interlocked).I can understand "Semaphore", "Monitor.TryEnter(object)" but I do not think these will work in this case.
Assume that,
pause variable value would be changed to
"false" in some other parts of code(not disclosed here) and this happens once in a while.At that point of time, all threads entered into "CriticalMethod"(i.e. in fraction of ns or micro sec) and one thread entered into lock and others are stuck before lock.
Thanks and Regards,
Anil