You have two choices: the easiest given your presented code is the volatile
keyword. declare needsToBeThreadSafe
as static volatile int
and that will guarantee that any thread that references that variable will get the "latest" copy, and the variable won't be cached within your code.
That being said, if you want to more generally ensure that M1()
and M2()
execute "atomically" (or at least exclusively of each other), then you want to use a lock
. The cleanest syntax is with a "lock block", like this:
private static object locker = new Object();
//..
public static void M1()
{
lock(locker)
{
//..method body here
}
}
public static void M2()
{
lock(locker)
{
//..method body here
}
}
As to which approach to take, that's up to you and should be determined by the code. If all you need is to ensure that a member assignment gets propagated to all threads and isn't cached, then the volatile
keyword is simpler and will do the job just fine. If it's beyond that, you may want to go with the lock
.