Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a piece of code exactly once with multithreading in mind?

I have a function which does "migration" from an old format to a new format. I need this to occur in the constructor of my object, but not the static constructor because an argument is needed. How can I have a piece of code only execute exactly one time?

For some context:

class Foo
{
  public Foo(string bar)
  {
    ShouldOnlyExecuteOnce(bar);
  }
}

and then usage could be (with each line a different thread)

var f = new Foo("bar");
var fb = new Foo("meh");
etc

How can I properly guard the "ShouldOnlyExecuteOnce" method?

Because this is a sort of "migration" type function, I want for the first object created to "win" and get to migrate the old data into this new object. Later objects that get constructed should not attempt to execute this function, even if their arguments are different

like image 736
Earlz Avatar asked Oct 28 '25 13:10

Earlz


1 Answers

You could use double check locking.

class Foo
{
    private static bool ShouldOnlyExecuteOnceExecuted = false;
    private static readonly object Locker = new object();

    public Foo(string bar)
    {
        SetShouldOnlyExecuteOnce(bar);
    }

    private void SetShouldOnlyExecuteOnce(string bar)
    {
        if(!ShouldOnlyExecuteOnceExecuted)
        {
            lock(Locker)
            {
                if(!ShouldOnlyExecuteOnceExecuted)
                {
                    ShouldOnlyExecuteOnce(bar);
                    ShouldOnlyExecuteOnceExecuted = true;
                }
            }
        }
    }
}
like image 194
Dustin Kingen Avatar answered Oct 31 '25 04:10

Dustin Kingen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!