I am trying to make a thread lock for a method so that only one thread can run it at a time. Although this is a well known issue and in C# there is the lock keyword to do it. I was trying to do it on my own and try to understand the depth of the problem of syncing multiple threads around one method.
private bool free = true;
public void start()
{
if(free== true)
{
free= false;
await DoTheWork();
free = true;
}
}
But I know that there might be a racing condition on the first line which is if(free==true)
and two threads can enter that statement block.
So I added a double lock which is the counter
as follow:
private bool free = true;
private int counter =0;
public void start()
{
if(free== true)
{
free= false;
counter++;
if(counter>1) return;
await DoTheWork();
free = true;
}
}
I know that designing an algorithm from scratch while there is a ready made library is not a good practice and it is considered (reinventing the wheel)... but for learning purposes I am interested to know what are the flaws in the algorithm mentioned above. Am I ok with that?
await
in a method that is notasync
. – svick Apr 27 at 19:31